Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Scheduled Tasks - Runs without Error but does not produce any output - Django PythonAnywhere
I have setup a scheduled task to run daily on PythonAnywhere. The task uses the Django Commands as I found this was the preferred method to use with PythonAnywhere. The tasks produces no errors but I don't get any output. 2022-06-16 22:56:13 -- Completed task, took 9.13 seconds, return code was 0. I have tried uses Print() to debug areas of the code but I cannot produce any output in either the error or server logs. Even after trying print(date_today, file=sys.stderr). I have set the path on the Scheduled Task as: (Not sure if this is correct but seems to be the only way I can get it to run without errors.) workon advancementvenv && python3.8 /home/vicinstofsport/advancement_series/manage.py shell < /home/vicinstofsport/advancement_series/advancement/management/commands/schedule_task.py I have tried setting the path as below but then it gets an error when I try to import from the models.py file (I know this is related to a relative import but cannot management to resolve it). Traceback (most recent call last): File "/home/vicinstofsport/advancement_series/advancement/management/commands/schedule_task.py", line 3, in <module> from advancement.models import Bookings ModuleNotFoundError: No module named 'advancement' 2022-06-17 03:41:22 -- Completed task, took 14.76 seconds, return code was 1. Any ideas on how I can get this working? It … -
Installing dependencies with requirements.txt by using Pip fails when deploying django app to elastic beanstalk
The app will not deploy because it fails to install Django after successfully installing other packages. Anyone know why this could be? requirements.txt: asgiref==3.5.2 attr==0.3.1 backports.zoneinfo==0.2.1 certifi==2022.6.15 charset-normalizer==2.0.12 Django==4.0.5 django-cors-headers==3.13.0 djangorestframework==3.13.1 idna==3.3 mysqlclient==2.1.0 numpy==1.22.4 python-dotenv==0.20.0 pytz==2022.1 requests==2.28.0 sqlparse==0.4.2 tzdata==2022.1 urllib3==1.26.9 Logs: 2022/06/17 02:47:39.485957 [INFO] Installing dependencies with requirements.txt by using Pip 2022/06/17 02:47:39.485969 [INFO] Running command /bin/sh -c /var/app/venv/staging-LQM1lest/bin/pip install -r requirements.txt 2022/06/17 02:47:41.833832 [INFO] Collecting asgiref==3.5.2 Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) Collecting attr==0.3.1 Using cached attr-0.3.1.tar.gz (1.7 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status 'done' Collecting backports.zoneinfo==0.2.1 Using cached backports.zoneinfo-0.2.1-cp37-cp37m-manylinux1_x86_64.whl (70 kB) Collecting certifi==2022.6.15 Using cached certifi-2022.6.15-py3-none-any.whl (160 kB) Collecting charset-normalizer==2.0.12 Using cached charset_normalizer-2.0.12-py3-none-any.whl (39 kB) 2022/06/17 02:47:41.833879 [INFO] ERROR: Could not find a version that satisfies the requirement Django==4.0.5 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, … -
How to add separate permission for a selected ModelAdmin in Django wagtail just like 'Page permissions'?
I am creating an application for teaching management in Wagtail. I create an AdminModal for 'Subjects'. I want to allow only selected user group to access a selected subject. Just like "Page permissions" in 'Add group'. Any idea how to do that? -
Splitting one field from model into two form input fields on django update view
I have this customer model with only one address field. class PullingCustomer(models.Model): code = models.CharField(verbose_name='Code', max_length=10, primary_key=True) name = models.CharField(verbose_name='Customer', max_length=255, blank=False, null=False) address = models.CharField(verbose_name='Address', max_length=255, blank=False, null=False) city = models.CharField(verbose_name='City', max_length=25, blank=True, null=True) def __str__(self): cust = "{0.name}" return cust.format(self) but on my form.py, I split it into two input, address 1 and address 2. class PullingCustomerForm(ModelForm): address1 = forms.CharField(max_length=155) address2 = forms.CharField(max_length=100) def __init__(self, *args, **kwargs): super(PullingCustomerForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.layout = Layout( .... Row( Column('address1', css_class = 'col-md-12'), css_class = 'row' ), Row( Column('address2', css_class = 'col-md-8'), Column('city', css_class = 'col-md-4'), css_class = 'row' ), .... class Meta: model = PullingCustomer fields = '__all__' Then I combine them again on view.py so I can save it. class PullingCustomerCreateView(CreateView): form_class = PullingCustomerForm template_name = 'pulling_customer_input.html' def form_valid(self, form): address1 = form.cleaned_data['address1'] address2 = form.cleaned_data['address2'] temp_form = super(PullingCustomerCreateView, self).form_valid(form = form) form.instance.address = str(address1) + ', ' + str(address2) form.save() return temp_form Since I want to use the same form layout on my update view, I need to split the address into two again. What is the best method to do that? class PullingCustomerUpdateView(UpdateView): model = PullingCustomer form_class = PullingCustomerForm template_name = 'pulling_customer_update.html' -
Django like filter for SQL query filter
How can i implement same django type filtering using SQL query. In django if i need to filter based on multiple column value i can again filter the query sets using .filter. For Example in Django: Model is Employee data = Employee.objects.all() if employee_department!='': data = data.filter(empdept=employee_department) if employee_location!='' data = data.filter(emploc=employee_location) How can i achieve this in SQL like filtering the query results -
occasionally i get Server Error (500) Missing staticfiles manifest entry
Before you mark it as duplicate, i did search and go throw many questions https://stackoverflow.com/search?q=[django]+Missing+staticfiles+manifest+entry my site works, but sometimes i get Server Error (500), And in logs i get: ValueError: Missing staticfiles manifest entry for 'css/jquery-ui.css' it's the first file in base.html. i think when staticfiles is missing a file, the site should stop at once. in staticfiles.json there is "css/jquery-ui.css": "css/jquery-ui.koi84nfyrp.css", mysite: storage = s3 cdn = cloudflare django = 4.0.4 P.S: in AWS bill center, there is $0.03 total, but i never get a bill or bay them any. Error Traceback ERROR [django.request:241] Internal Server Error: / Traceback (most recent call last): File "/django-my-site/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/django-my-site/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/django-my-site/venv/lib/python3.8/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/django-my-site/venv/lib/python3.8/site-packages/django/template/response.py", line 92, in rendered_content return template.render(context, self._request) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 62, in render return self.template.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 175, in render return self._render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render return self.nodelist.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 958, in render_annotated return self.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line … -
How to make Django's ImageField app specific?
I've read through a few answers/articles at these links, but am still confused as all of them SEEM to be slightly different than what I'm after: here here here here here I am looking to make use of Django's ImageField function for uploading images from my admin page, to my portfolio/blog's app space. My folder structure looks like this: Portfolio_Blog_Website |---personal_portfolio_project |---projects_app |---migrations |---static |---img |---templates So I want to upload images to/display on the template from, the app > static > img folder. Currently, I have STATIC_URL = 'static/' set, and I'm manually drag and dropping image files into that folder, and using models.FilePathField(path="/img") in the model, and displaying them (in a for loop) with <img src="{% static project.image %}">, which works. I want to switch to be able to upload images from the admin page, and then display them on the app's page like they're supposed to. From what I've read, we have to define a MEDIA_ROOT and MEDIA_URL variable to use with models.ImageField(upload_to="img/"). The problem I see is that MEDIA_ROOT needs to be an ABSOLUTE path to the folder, which I COULD set as \\C:\Portfolio_Blog_Website\projects_app\static\img, however this isn't necessarily what I want because I'm specifically targeting the … -
Grouping ModelMultipleChoiceField in custom group and permissions form in django
I'm to implement a custom form for assigning permissions for groups in django. I have several apps in the project and every one defines its own set of permissions within its own 'AppPermissions' model. I'm currently using a ModelMultipleChoiceField with a CheckboxSelectMultiple widget. Like so: app_permissions = Permission.objects.filter(content_type__model='apppermissions') permissions = GroupedModelMultipleChoiceField( app_permissions, widget=forms.CheckboxSelectMultiple ) Now this already displays the checkboxes I need for displaying the permissions but a requirement is that they must be grouped by app. In a header/content fashion: App1_Name_Header [] App1_name_Permission1 [] App1_name_Permission2 [] App1_name_Permission3 App2_Name_Header [] App2_name_Permission1 [] App2_name_Permission2 etc... Is there a way to implement this? I'm very inexperienced with django so if there's a way of building a widget or a custom field that can accomplish this, any guidance will be appreciated. -
django.core.exceptions.ImproperlyConfigured: No default throttle rate set for 'jwt_token' scope
It was working fine two days ago. But now I am getting this above error. I am not sure what is the issue. When I call jwt/token/ for simple jwt authentication in django rest framework, I get this error. My base.py settings is as follows: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( # "rest_framework.authentication.SessionAuthentication", # "rest_framework.authentication.TokenAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", ), "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", "DATETIME_FORMAT": "%B %d, %Y %H:%M:%S", "DEFAULT_THROTTLE_RATES": { "jwt_token": "5/minute", "user_registration": "5/day", "otp_email_verification": "5/day", "password_reset": "5/day", "google_registration": "5/day", "resend_email_verification": "5/day", "apple_registration": "5/day", "facebook_registration": "5/day", }, } The problem in the api is follows: {{local}}api/v1/users/jwt/token/ My traceback: Traceback (most recent call last): File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\django\views\decorators\debug.py", line 89, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "E:\lvl9\merosiksha\merosiksha\users\api\v1\views.py", line 172, in dispatch return super().dispatch(*args, **kwargs) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "E:\lvl9\merosiksha\myvenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "E:\lvl9\merosiksha\myvenv\lib\site-packages\rest_framework\views.py", line 497, in dispatch self.initial(request, *args, **kwargs) … -
django-s3direct 2.0.2 admin upload not displaying in Django 3.2
I am in the process of upgrading my versions after a period of neglect. Previously I was on Django==2.2.24 and django-s3direct==1.1.5. Downgrading django-s3direct to 1.1.5 but keeping Django 3.2 restored the functionality of django-s3direct, so the issue seems to lie within the newer version of django-s3direct itself. In the admin the S3 direct upload form is not showing up -- it should appear in the space to the right of "Local image:" in the screenshot below: However, all the markup for the element is in the source of the page. I discovered that the CSS from /static/s3direct/dist/index.css appears to be hiding it (what you see below is the CSS straight from the file; it was not modified by any JS that ran on the page). s3direct worked prior to this upgrade. I'm not attempting anything custom in the code. models.py: class Image(models.Model): local_image = S3DirectField(dest='misc', null=True, blank=True) admin.py: admin.site.register(Image) I also don't have anything custom running on my admin pages. All the other JS/CSS files pulled into this page are files included with the Django admin. I ensured that all I followed all set-up steps for the latest version (I added my access credentials directly to settings.py). I don't see … -
Adding a multiple file field to a Django ModelForm
I'm wanting to create a form that allows multiple image uploads. I've got a Listing model that looks like this: class Listing(models.Model): location = models.CharField("Address/Neighborhood", max_length=250) class ListingImage(models.Model): listing = models.ForeignKey( Listing, related_name="images", on_delete=models.SET_NULL, null=True, ) image = models.ImageField() I'm using django-crispy-forms to create the form on the page but I cannot figure out how to get the listing field onto the page. class ListingModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( Fieldset( "Location", Div("location", css_class="col-md-12 col-lg-6") ) ) class Meta: model = Listing fields = "__all__" -
Why is the >= operator in python working like a > in a if statement?
I have an if statement that checks whether whatever is submitted in a Django form is greater than or equal to the listing_price (initial price of the item) and greater than all other bids before saving. The second part of the conditional is working, but the form will only save if the submitted value is greater than the listing_price, not equal. The greater than or equal to operator is working like a greater than operator instead. What could be causing the problem and how do you fix it? views.py def listing(request, id): #gets listing listing = get_object_or_404(Listings.objects, pk=id) listing_price = listing.bid bid_form = BidsForm() #code for the bid form bid_obj = Bids.objects.filter(listing=listing) other_bids = bid_obj.all() max_bid =0 for bid in other_bids: if bid.bid > max_bid: max_bid = bid.bid if request.method == "POST": bid_form = BidsForm(request.POST) #checks if bid form is valid if bid_form.is_valid(): new_bid = float(bid_form.cleaned_data.get("bid")) if (new_bid >= listing_price) and (new_bid > max_bid): bid = bid_form.save(commit=False) bid.listing = listing bid.user = request.user bid.save() else: return render(request, "auctions/listing.html",{ "auction_listing": listing, "form": comment_form, "comments": comment_obj, "bidForm": bid_form, "bids": bid_obj, "message": "Your bid needs to be equal or greater than the listing price and greater than any other bids." }) else: return … -
Is that safe too use same venv for different projects?
I'm trying to learn Django framework, and I made a Virtual Environment include Django 4 and python 3.10. Is it safe to use this VENV for all my future projects or should I make new for each one? Consider that those projects will be make for real persons and they expect high security. -
Is the any import problem in this code?I tried many solutions like changing app name but none worked for me
from rest_framework import serializers from rest_framework import hospital class hospitalsSerializer(Serilizers.Modelserializer): class Meta: model=hospital field='all' //this is my serializers.py -
Adding button to a field in a form to add data from another form Django
So, I have this html file with a model form and I would like to add a button '+' to just one field of the form to to open a modal with another smaller form to fill out and just take information from one column. I already have the way to open the modal and the second form, in the database I am guessing I will need a foreign key, but I am still trying to figure out how to implement the button right next to the field. So far, I have this in my forms.py file: class contractsform(forms.ModelForm): class Meta: model = Contratos fields = '__all__' widgets = { 'name': forms.TextInput(attrs ={'class': 'form-control'}), 'contractee': forms.TextInput(attrs={'class': 'form-control'}), 'contractor': forms.TextInput(attrs={'class': 'form-control'}), 'start': forms.NumberInput(attrs={'class': 'form-control', 'type': 'date'}), 'end': forms.NumberInput(attrs={'class': 'form-control', 'type': 'date'}), 'cost': forms.NumberInput(attrs={'class': 'form-control'}), 'type': forms.Select(attrs={'class': 'form-select'}), 'department': forms.Select(attrs={'class': 'form-select'}), 'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}), 'product': forms.TextInput(attrs={'class': 'form-control'}), 'attached_file': forms.FileInput(attrs={'class': 'form-control'}), 'notification': forms.CheckboxInput(attrs={'class': 'form-check-input'}), } I added attrs just to make the fields pretty. I would like to add it to the contractor field, with bootstrap 5, but I am new to Django and the manual confused me a little bit. -
Django CSRF verification failed even with @csrf_exempt
I've got a web service written in Django that has a py file with a bunch of view functions that are decorated with @csrf_exempt. It's all working as it has been for years. I recently added another function and entry in urls.py. I used the same pattern as all the other view functions -- decorated with @csrf_exempt, but for this one function the server responds with a CSRF verification failed. a snippet of my urls.py url(r'changepassword$', websvc2_account.changepassword), url(r'resetpassword$', websvc2_account.resetpassword), url(r'getcodetodeleteaccount$', websvc2_account.getcodetodeleteaccount), url(r'deleteaccountwithcode$', websvc2_account.deleteaccountwithcode), url(r'setuserdetails$', websvc2_account.setuserdetails), The function I added: @csrf_exempt def getcodetodeleteaccount(request): ... These views are called from mobile apps, so I do not want CSRF and all of them are decorated with @csrf_exempt. This new function is the only one that doesn't work. Any help or clues would be appreciated. Thanks -
How to display few fields from another model instead of one <select> field in Django Admin
everyone. I have two models linked one-to-many relationships ModelA: field_1 .. field_n ModelB: some_field = ... field = ForeignKey(ModelA) What i need to do so that when opening an entry of ModelB in Admin site, other then all ModelB fields, all fields of ModelA are displayed instead of field? Sorry for my english 😬 -
Cloud Foundry Django app `cf push` logs the error `port 5432 failed: Connection refused`
I am deploying a basic Django app with Cloud Foundry. The app appears to be unable to connect to or authenticate with the database. I encounter the error after I run the cf push -f manifest.yml command. It returns Start unsuccessful and suggests I look at the logs with the cf logs app-name-1 --recent command. The logs contain this error: ERR django.db.utils.OperationalError: connection to server at "server-name.region-name.rds.amazonaws.com" (ip.redacted), port 5432 failed: Connection refused ERR Is the server running on that host and accepting TCP/IP connections? The app's repo contains a manifest.yml that specifies an application name app-name-1 and a service service-name-psql-db. This app exists, as you can see from the output of the cf apps command: Getting apps in org org-name / space space-name as user-name.. name requested state processes routes app-name-1 started web:0/1 app-name-1.app.domain.com Further, the app is hooked up to a database service as you can see from the output of the cf services command: Getting services in org org-name / space space-name as user-name... name service plan bound apps last operation broker upgrade available service-name-psql-db aws-rds micro-psql app-name-1 update succeeded aws-broker The credentials I am trying to use to connect to the database seem correct to me. … -
wsgi:error pid 131476:tid 140411361216256 remote 200.110.48.158:35204 ModuleNotFoundError: No module named 'django.core'
[Thu Jun 16 20:32:08.505090 2022] [wsgi:error] [pid 131476:tid 140411386394368] [remote 193.32.127.157:53433] Traceback (most recent call last): [Thu Jun 16 20:32:08.505133 2022] [wsgi:error] [pid 131476:tid 140411386394368] [remote 193.32.127.157:53433] File "/root/novo-ai-api-main/backend/server/server/wsgi.py", line 18, in <module> [Thu Jun 16 20:32:08.505139 2022] [wsgi:error] [pid 131476:tid 140411386394368] [remote 193.32.127.157:53433] from django.core.wsgi import get_wsgi_application [Thu Jun 16 20:32:08.505159 2022] [wsgi:error] [pid 131476:tid 140411386394368] [remote 193.32.127.157:53433] ModuleNotFoundError: No module named 'django.core' [Thu Jun 16 20:48:58.603180 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] mod_wsgi (pid=131476): Failed to exec Python script file '/root/novo-ai-api-main/backend/server/server/wsgi.py'. [Thu Jun 16 20:48:58.603316 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] mod_wsgi (pid=131476): Exception occurred processing WSGI script '/root/novo-ai-api-main/backend/server/server/wsgi.py'. [Thu Jun 16 20:48:58.603447 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] Traceback (most recent call last): [Thu Jun 16 20:48:58.603477 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] File "/root/novo-ai-api-main/backend/server/server/wsgi.py", line 18, in <module> [Thu Jun 16 20:48:58.603483 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] from django.core.wsgi import get_wsgi_application [Thu Jun 16 20:48:58.603506 2022] [wsgi:error] [pid 131476:tid 140411361216256] [remote 200.110.48.158:35204] ModuleNotFoundError: No module named 'django.core' These are my all working files **#000-default.conf** <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating … -
Update To Django 4.0.5 in an existing web app in Pythonanywhere
I have got a web app working on the web and I want to update the Django version from 3.1 to 4.0.5 because of it’s posible with the new version to solve a problem when an annotate query doesn’t find results and to get 0 instead of None. How can I change the version of Django easily without delete and deploy again the web app? Is possible to go into the virtual environment and simply update Django or is necessary something more (like change requirements before or something more)? -
How to return extra dictionary information in queryset via Django ListViewApi?
Currently my query is returning following response using ListViewApi [ { task: x year: y total_value: 10 },{ task: p year: e total_value: 10 } ] I want to display following extra information in dictionary format using django queryset [ { task: x year: y total_value: 10, category_data:[ { type: b, value: 3 },{ type: b, value: 7 } ] },{ task: p year: e total_value: 10 } ] -
Django: Switch a form in template depending on choice field
I am looking for a way to switch and display a form in template, depending on choice in CharField in another form. My app has the following models: class Damage(models.Model): damage_place = models.CharField() damage_date = models.DateField() class DamageType1(models.Model): damage = models.ForeignKey(Damage) ... class DamageType2(models.Model): damage = models.ForeignKey(Damage) ... class DamageType3(models.Model): damage = models.ForeignKey(Damage) ... Damage model has a DamageForm(forms.ModelForm) that is filled in by another user. Each DamageType model has different fields (marked as ... for simplicity) and own DamageTypeForm1(forms.ModelForm), DamageTypeForm2(forms.ModelForm) and DamageTypeForm3(forms.ModelForm). There is also a form in a template specifying which DamageType to choose: class DamageSpecify(forms.Form): DAMAGE_CHOICES = [ ('DamageType1', 'DamageType1'), ('DamageType2', 'DamageType2'), ('DamageType3', 'DamageType3'), ] damage_type = models.CharField(choices=RODO_CHOICES) And now, after choose specific damage_type in DamageSpecify I would like to display the filled DamageForm and empty DamageType(1, 2 or 3) in template to fill and save both forms. How could this be done? -
Django Allauth redirect to localhost instead of 127.0.0.1
I have a custom User class, which is shown on the main page: After a successful log in, django redirects me to the localhost page shown above. I also have an API that connects the backend to the frontend. However, it communicates with http://127.0.0.1/, which has a different user. In my views I only have: urlpatterns = [ path('', views.index, name='index'), path('api/tableEntries', views.ReactView.as_view(), name="api"), path('api/getUser', views.getUser.as_view(), name="getUser"), path('accounts/', include('allauth.urls')), ] And in my settings, I have the redirect variable set like this: LOGIN_REDIRECT_URL = 'index' I have 2 questions: I read in other threads that localhost and 127.0.0.1 sometimes resolve to different domains, and share different cookies. But why do they resolve to different domains? How do i fix it so that the redirect goes to 127.0.0.1 and I can access it with an API call? -
raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed
I use Django and every time when I try to send email I get this response Internal Server Error: /order/ Traceback (most recent call last): File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Daniil\Desktop\Admin\py\qazpoligrah1\main\views.py", line 53, in post email.send() File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\mail\message.py", line 298, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\mail\backends\smtp.py", line 124, in send_messages new_conn_created = self.open() File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\mail\backends\smtp.py", line 91, in open self.connection.login(self.username, self.password) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 739, in login (code, resp) = self.auth( File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 642, in auth (code, resp) = self.docmd("AUTH", mechanism + " " + response) File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 432, in docmd return self.getreply() File "C:\Users\Daniil\AppData\Local\Programs\Python\Python39\lib\smtplib.py", line 405, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed my settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.mail.yahoo.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'email@yahoo.com' EMAIL_HOST_PASSWORD = 'password' my views def post(self,request): print(request.POST.get('mail'), request.POST.get('type')) prod_type = models.ProductTypes.objects.filter(pk = request.POST.get('type')) order_msg = prod_type[0].name email = EmailMessage('Qazpoligraph', order_msg, settings.EMAIL_HOST_USER, to= (request.POST.get('mail'),)) email.send() return redirect('/') I tryed to change the EMAIL_PORT and the EMAIL_HOST but nothing … -
How does djagno update urls when you add a model to an app?
If I have an app (blog) and I create a posts model and then add a schedule model how are the urls for schedule created? Are they imported with the blog.urls like the posts in 3 line below? urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls')), path('accounts/', include('django.contrib.auth.urls')) ] Then how would django reference the schedule model views? Is it path('schedule/,views.scheduleDetail.as_view(),name='sidebar.html') in the myblog.urls? Thanks