Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError: unsupported operand type(s) for += 'set' and 'list'
File "C:\Users\sungk\Git\django_website\my_site_prj\urls.py", line 31, in urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) TypeError: unsupported operand type(s) for += 'set' and 'list' How to slove this problem... please~ urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Change URL Path for View Profile Page - Django
How would one go about creating a user-profile page that other users can view without being able to edit the profile unless they are the user? The thing I'm trying to work out is how the url routing would work, is it best practice to store a user's profile on a profile/ or <user_id> page and then load in the individual user's data like recent posts using the username or id passed through the url? Also would this be handled by the one view and template and just use {% if request.user == profile.user %} to display things like edit profile etc? my problem is any user can edit for others there profiles when he edit url for example my id is www.test.com/profile/44/ and other user have this id www.test.com/profile/40/ okay ,, now when i edit the link to be 40 not 44 i can access and edit the second user ! how to fix that models.py : class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() def __str__(self): return self.user urls.py : from django.urls import path from blog_app.views import ProfileView urlpatterns = [ path('profile/<int:pk>/', ProfileView.as_view(), name='profile'), ] forms.py … -
django stripe create charge
When i call this method. charge = stripe.Charge.create( amount=request.POST.get('amount', ''), currency=request.POST.get('currency', ''), source=request.POST.get('source', ''), idempotency_key=request.POST.get('idempotency_key', ''), # https://stripe.com/docs/api/idempotent_requests description=request.POST.get('description', ''), statement_descriptor=request.POST.get('statement_descriptor', ''), ) It create success a payment what i checked in dashboard. I am using test API, i see anyone can create payment without submitting their card number. why? is it secure? Can you please tell me what does these success means? how can i charge by card and it should show success in stripe dashboard? any ideas? -
Using Django admin application AND disabling session middleware?
I am building a django server for an API that relies on JWT (or Token based - https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication) authentication for our users. I don't need session based authentication for any purpose. It creates an unnecessary query on each request, and also authenticates users when I don't want to authenticate them (I want browsers to only authenticate when it includes an Authentication header in the request, and stay AnnonymousUser otherwise. This is because it creates issues in some of my middlewares where I verify if I am dealing with a guest or a authenticated user). However, the issue comes when I try to use the admin application as well (I can't imagine building this app without the use of the django admin page). When I remove the session-related middlewares:(django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware) from my settings file, I get the following error when I do a runserver: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. Can someone think of a workaround where I can disable sessions in … -
React/Django: Database works, but React Is not Rendering the Views
I am trying to send information from my API and render it via React, but I get a blank screen. I am newer to fullstack development, so I am not sure where the disconnect. I can view dataentries I've created in the api, but cannot render these. I tried rendering the data is my models.py with my App.js App.js import React, { Component } from "react"; import { render } from "react-dom"; class App extends Component { constructor(props) { super(props); this.state = { data: [], loaded: false, placeholder: "Loading" }; } componentDidMount() { fetch("events/api") .then(response => { return response.json(); }) .then(data => { this.setState(() => { return { data, loaded: true }; }); }); } render() { return ( <div> {this.state.data.map(events => { return ( <div> Event: {events.title} Details {events.details} </div> ); })} </div> ); } } export default App; const container = document.getElementById("api"); render(<App />, container); models.py from django.db import models # Create your models here. class Events(models.Model): title = models.CharField(max_length=100) details = models.CharField(max_length=100) Please let me know if you need anything else. -
Django - Translation
I have this function that receives a location and returns a location code for it. def match_locations(location): if _('Everywhere') in location: location_code = 'loc_1' return location_code which gets called from this request: def return_more_jobs(request): url_parameter = request.GET.get("q") if url_parameter is not None: url_parameters = url_parameter.split('-') where = match_locations(url_parameters[1]) ... return HttpResponse(json.dumps(res), content_type="application/json") When I try to get the location code of the translation of 'Everywhere' it doesn't match. I have set the translation for 'Everywhere' in the .po file, but it doesn't work in this case. Thank you for any suggestions -
Page not found (404) Request Method: GET Request URL: http://localhost:8000/%23 Raised by:challengeide.views.send_challenge_request
This is challenge page When we go to ide page using the challenge button on the bottom and then click on submit button there then data is getting stored in database and function is running fine. But when I click on accept button and go to ide page and then click submit then data is not getting updated in database so basically function is not running and directly giving error 404 page not found. this is the error i am getting from django.conf.urls import url,include from django.urls import path,re_path from . import views app_name = 'challengeide' urlpatterns = [ path('challengeide/<int:sr_no>', views.show, name='show'), url('challengeide', views.qtn,name='test'), url('challenge/', views.challengeide, name='challengeide'), url('#', views.send_challenge_request, name='send_challenge_request'), ] this is my url.py <small class="float-right"> <div class="btn-group" style="display: inline-block;"> <form method="POST" action="{% url 'challengeide:show' r_request.qtn_id %}">{% csrf_token %} <button class="btn btn-success mr-2" type="submit" value="Accept">Accept</button> </form> </div> </small> this is my template for challenge page which has accept button <a class="btn btn-primary mr-2" href="{% url 'challengeide:send_challenge_request' %}" >Submit</a this is my template for challenge ide which has the submit button def send_challenge_request(request): user = get_object_or_404(User, id=to_id) print(user) score = ChallengeDemo.objects.filter(from_id=request.user,to_id=user,qtn_id=a) print(score) if(len(score)==0): print("dataintial") print(to_id) global data2 #user = data2 print(request.user) print(user) print("dataentry") entry = ChallengeDemo( from_id=request.user, to_id=user, score1 = … -
Serving static files from private s3 in django
Is there a way to serve static files from private s3. i know there are plenty of tutorials (like https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html) that help u in serving static files from public buckets. i serve my media files. and i get a signed url which will timeout after 120s. can i not get a similar url for static files? i am sorry if this sounds stupid. STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets'),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') DEFAULT_FILE_STORAGE ='storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = "***************" AWS_SECRET_ACCESS_KEY ="**********" AWS_STORAGE_BUCKET_NAME = "*********" AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_DEFAULT_ACL = None AWS_QUERYSTRING_EXPIRE = 120 AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' this is my settings.py and my media files... i get a signed url when i query it.... but my static files ... i dont get a signed url (i.e. it looks like https://bucketname.s3.us-east-2.amazonaws.com/Path/file_fileext/) so i get a 403 forbidden note: my bucket iam user has AmazonS3FullAccess permission my bucket policy is EMPTY my block all public access is ON AND this is my cors policy [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD", "POST", "PUT", "DELETE" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ]``` -
showing error in map while fetching data in Reactjs after authentication in CRUD django REST api?
i am trying to do a CRUD app with backend in Django Rest Api and in frontend it would be react-hooks. The main functionality will be, after authentication it would show tasks created by the user and only user would see and edit, delete etc his own tasks. i have uploaded the API in heroku and Here is Api link and here is the openapi look. and you can find the source code in the github and here is the codesandbox for frontend FYI: i couldn't link the backend with the codesandbox frontend but in localhost frontend can communicate with the backend django part. i have used corsheaders to separate frontend and backend. i am practicing in this way just because the backend API would be reusable. i am not sure whether it is a professional practice or not. though i couldn't link my api with the codesandbox and it is for the show of my whole code. in dashboard.js, the below part is working: useEffect(() => { if (localStorage.getItem("token") === null) { window.location.replace("http://localhost:3000/login"); } else { fetch("http://127.0.0.1:8000/api/auth/user/", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Token ${localStorage.getItem('token')}`, }, }).then(res=>res.json()) .then(data=>{ setUserEmail(data.email); setLoading(false) setUsername(data.username) }) } }, []); Here the … -
Unable to POST Values And Create a Derived Value in Django
I am new to Django and still learning. Currently, I have a running code below which allows me to input data but I am unable to POST it to DB. I am not sure what I've done wrong. Model class ManHour(models.Model): station_choices = ( ('alpha','A'), ('beta', 'B'), ('gamma','G'), ) station = models.CharField( max_length=3, choices=station_choices, ) date = models.DateTimeField(auto_now=True) ops_1 = models.DecimalField(max_digits= 5, decimal_places= 3, default = 1) ops_2 = models.DecimalField(max_digits= 5, decimal_places= 3, default = 1) ops_3 = models.DecimalField(max_digits= 5, decimal_places= 3, default = 1) Form from django import forms from webapp.models import ManHour class InputForm(forms.ModelForm): class Meta: model = ManHour fields = ['station', 'ops_1', 'ops_2', 'ops_3'] Views def form_page(request): if request.method == 'POST': properties_Form = InputForm(request.POST) if properties_Form.is_valid(): properties_Form.save() return redirect('home') context ={} context.update(csrf(request)) context['request'] = request context['form']= InputForm() return render(request, "form.html", context) HTML {% block content %} <form target="upload_frame" action="" method="post" enctype="multipart/form-data" > {% csrf_token %} {{ form.as_p }}<br> <input type="submit" name="submit" value="Upload" id="submit"> </form> {% endblock %} Given the above code I am not sure why I am unable to post values to DB. My second question is that I want to create a derived field that sums ops1 and ops2 and I want it show to … -
How to customize the appearance of the Django change password form
How to customize the appearance of the Django change password form , i tried this but nothing happened i don't know why , any ideas ? forms.py : from django.contrib.auth.forms import PasswordChangeForm class MyPasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["old_password"].widget = forms.PasswordInput(attrs={"class": "form-control"}) self.fields["new_password1"].widget = forms.PasswordInput(attrs={"class": "form-control"}) self.fields["new_password2"].widget = forms.PasswordInput(attrs={"class": "form-control"}) urls.py : # Change Password path( 'change-password/', auth_views.PasswordChangeView.as_view( template_name='user/commons/change-password.html', success_url = '/' ), name='change_password' ), views.py : from django.contrib.auth.views import PasswordChangeView from blog_app.forms import MyPasswordChangeForm class PasswordChangeView(PasswordChangeView): form_class = MyPasswordChangeForm template_name = "user/commons/change-password.html" change_password.html : <div class="form-group"> <form method="post"> {% csrf_token %} {{ form.as_p }} <a href="{% url 'home' %}">Back</a> <button type="submit">Submit</button> </form> </div> -
How to show only a few Many-to-many relations in DRF?
If for an example I have 2 models and a simple View: class Recipe(model.Model): created_at = model.DateField(auto_add_now=True) class RecipeBook(model.Model): recipes = model.ManyToManyField(Recipe) ... class RecipeBookList(ListAPIView): queryset = RecipeBook.objects.all() serializer_class = RecipeBookSerializer ... class RecipeBookSerializer(serializers.ModelSerializer): recipe = RecipeSerializer(many=True, read_ony=True) class Meta: model = RecipeBook fields = "__all__" What would be the best way, when showing all Restaurants with a simple GET method, to show only the first 5 recipes created and not all of them? -
Django Query how to sum returned objects method
I have a model: class TimeStamp(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) t_in = models.DateTimeField(_("In"), auto_now=False, auto_now_add=False) t_out = models.DateTimeField( _("Out"), auto_now=False, auto_now_add=False, blank=True, null=True) class Meta: verbose_name = _("TimeStamp") verbose_name_plural = _("TimeStamps") def __str__(self): return str(f'{self.t_in.date()} {self.user.get_full_name()}') def get_absolute_url(self): return reverse("TimeStamp_detail", kwargs={"pk": self.pk}) def get_total_hrs(self): if self.t_out: t_hrs = abs(self.t_out-self.t_in).total_seconds()/3600 else: t_hrs = '0' return str(t_hrs) then in my views.py def timeclock_view(request): week_start = timezone.now().date() week_start -= timedelta(days=(week_start.weekday()+1) % 7) week_end = week_start + timedelta(days=7) obj = request.user.timestamp_set.filter( t_in__gte=week_start, t_in__lt=week_end) obj.aggregate(total_hrs=Sum('get_total_hrs')) if obj: last = obj.last() context = {'obj': obj, 'last': last, 'week_start': week_start, 'week_end': week_end, 'week_total': total_hrs, } else: context = {} return render(request, 'timeclock/timeclock_view.html', context) how do i write this to get a sum of the hrs for the queryset? obj.aggregate(total_hrs=Sum('get_total_hrs)) is giving me an error django.core.exceptions.FieldError: Cannot resolve keyword 'get_total_hrs' into field. Choices are: description, id, note, note_set, pw, t_in, t_out, user, user_id -
How to solve MultipleObjectsReturned with ForeignKeywidget in django-import-export
I have a resource that should help me import data into my model but it doesn't work. I have tried all the options I could but to no success. This is the resource. class ImportStudentsResource(resources.ModelResource): klass = fields.Field(attribute = 'class',column_name='class',widget= ForeignKeyWidget(Klass,'name')) stream = fields.Field(attribute = 'stream',column_name='stream',widget=ForeignKeyWidget(Stream,'name')) gender = fields.Field(attribute = 'gender',column_name='gender', widget=ForeignKeyWidget(Gender, 'name')) school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name')) class Meta: model = Students fields = ('school','adm','name','kcpe','klass','stream','gender','notes') import_id_fields = ('adm',) import_order = ('school','adm','name','kcpe','klass','stream','gender','notes') This is the data to import into the model through the resource This is the Traceback. Traceback (most recent call last): File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "D:\Python\Django\Links Online Exams\Links_Online_Results\students\views.py", line 52, in post result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 741, in import_data return self.import_data_inner(dataset, dry_run, raise_errors, using_transactions, collect_failed_rows, **kwargs) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 788, in import_data_inner raise row_result.errors[-1].error File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 658, in import_row self.import_obj(instance, row, dry_run) File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 512, in … -
Django extra_context URL
I am trying to figure out how to pass in extra_context that takes a User instance's username and uses it for constructing the User's profile URL, whether it be using extra_context or other methods I have tried, such as get_context_data(). Note: I have included different attempts as one. views.py from django.contrib.auth.models import User from django.contrib.sites.shortcuts import get_current_site from django.shortcuts import render from django.urls import reverse from allauth.utils import get_request_param from django.views import View from .models import CandidateProfile from .forms import CandidateProfileForm from allauth import app_settings from allauth.account.views import SignupView from allauth.account.utils import complete_signup, passthrough_next_redirect_url from allauth.exceptions import ImmediateHttpResponse class CandidateSignUpView(SignupView, View): def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def get_context_data(self, **kwargs): ret = super(SignupView, self).get_context_data(**kwargs) form = ret["form"] email = self.request.session.get("account_verified_email") if email: email_keys = ["email"] if app_settings.SIGNUP_EMAIL_ENTER_TWICE: email_keys.append("email2") for email_key in email_keys: form.fields[email_key].initial = email login_url = passthrough_next_redirect_url( self.request, reverse("account_login"), self.redirect_field_name ) redirect_field_name = self.redirect_field_name site = get_current_site(self.request) redirect_field_value = get_request_param(self.request, redirect_field_name) username = self.user.username ret.update( { "login_url": login_url, "redirect_field_name": redirect_field_name, "redirect_field_value": redirect_field_value, "site": site, "username": username, } ) return ret def form_valid(self, form): self.user = form.save(self.request, commit=False) self.user.is_candidate = True self.user.save() extra_context = {'username': self.user.username} success_url = f'profile/{self.user.username}/' try: return complete_signup( self.request, … -
social auth app django Google Auth After Register Say Your Account Is ALready Exist
I Put Social Google Auth In My Website Complete Register And I Can Login in My Website First Time With One Google Account But At Second Time Say To Me Your Account Exist And Dont Just Like Normal Login To Website Becuase I Registered Before And Give Me Error That Your Account Already Exist I Want To Now How To Fix It . -
Django PasswordResetConfirmView not setting new password
I am trying to use a Custom PasswordResetConfirmView template. Since the default form has no styling and I am trying to put a custom class in it. Here is my forms.py: from django.contrib.auth.forms import PasswordResetForm class UserPasswordChangeForm(PasswordChangeForm): def __init__(self, *args, **kwargs): super(UserPasswordChangeForm, self).__init__(*args, **kwargs) new_password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Password', })) new_password2 = forms.CharField(label='Conform Password', widget=forms.PasswordInput(attrs={ 'class': 'form-control', 'placeholder': 'Confirm Password', })) Here is urls.py: from django.contrib.auth import views as auth_views path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='registration/password_reset_confirm.html', form_class=UserPasswordChangeForm, success_url=reverse_lazy('password_reset_complete')), name='password_reset_confirm'), When I put new_password1 and new_password2, it does not save the new password, or even show erorrs. -
How can i compare two DateTimeFields with current time
Event has two DateTimeField's and i need to compare them to the actual date time in a same method. from django.utils import timezone event_starts = models.DateTimeField(_("Event starts")) registration_closes_at = models.DateTimeField( _("Registration ends:"), null=True, blank=True ) This is what i have tried, but it doesn't work. So what i need is: If event has been started or registration was closed user can not attend this event. def is_registration_open(self): now = timezone.now() passed_registration = now > self.registration_closes_at passed_start = now > self.event_starts if not passed_registration or not passed_start: return And tried this: def is_registration_open(self): if ( not timezone.now() > self.registration_closes_at or not timezone.now() > self.event_starts ): return Here is a fail: '>' not supported between instances of 'datetime.datetime' and 'NoneType' When i compare only event_starts everything is working fine. Thanks for help! -
Django two or more droplets sharing same sqlite database?
For one of my use-case I had to use a local sqlite database for one of my model. But as I am using load-balancing for my project, I cannot use two databases as all droplets would have different database. So, I was trying to find a way in which I can use a single local database in one of my droplet and then let other droplets read/write from this database. Is there any way to achieve this? -
Changing the size of bootstrap cards in a Django project?
I'm working on a simple Django project with bootstrap. I have a set of cards being displayed on a page, and the cards are showing just fine (Don't mind the place holder images). I've been reading the bootstrap docs about cards, but since I have less knowledge of CSS than I'd like, I can't figure out how to simply change the size of the cards so they are larger and stacked in rows instead of one column. This is my HTML template for this page. It just uses a for-loop to go through my projects and make a card for each. You can see I have the title and text worked out, and the URL to 'See Details'. {% extends "base.html" %} {% load static %} {% block page_content %} <h1>Projects</h1> <div class="row"> {% for project in projects %} <div class="col-md-4"> <div class="card mb-2"> <img class="card-img-top" src="{% static project.image %}"> <div class="card-body"> <h5 class="card-title">{{ project.title }}</h5> <p class="card-text">{{ project.description }}</p> <a href="{% url 'project_detail' project.pk %}" class="btn btn-primary"> See Details </a> </div> </div> </div> {% endfor %} </div> {% endblock %} The Base.html is just linking to the bootstrap and all the html for the top of the page. Hopefully … -
How to Update Multiple Images of product in django
how to edit images of product to form edit product models.py: class Product(models.Model): title = models.CharField(max_length=200, verbose_name='title') text = models.CharField(max_length=200, verbose_name='text') thumbnail = models.ImageField(upload_to=get_file_path, verbose_name='thumbnail') def __str__(self): return self.title class Product(models.Model): id_product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE, related_name='products',verbose_name='product') photo = models.ImageField(upload_to=get_file_path, verbose_name='photo') thanks -
fix problem any user can change password for admin user site using UserCreationForm - django
I am new in Django and even after trying thoroughly to find an answer for this question, I couldn't find any. the problem is any user can change password for admin user site using UserCreationForm , i mean any user can use reset password form he can change my profile in admin page i don't want allow users change admin profile how to fix this problem ? -
Model UserProfile object has no attribute 'save'
So, I am trying to create an API user registration endpoint on my Django + DRF project. Whenever a user is registered it should create also a user profile. But, I am getting this error while printing sys.exc_info(): AttributeError("'UserProfile' object has no attribute 'save'") I am reading how to create objects in Django documentation says: from blog.models import Blog b = Blog(name='Beatles Blog', tagline='All the latest Beatles news.') b.save() So, I have tried that, I guess; this is where everything stops working: try: profile = UserProfile(user=user) if 'picture' in request.data: profile.picture = request.data['picture'] profile.save() except: print('USER PROFILE CREATION', sys.exc_info()) try: user.delete() except: print('USER DELETE ON PROFILE CREATION ERROR', sys.exc_info()) return Response(result, status=500) And this is my model definition: class UserProfile(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) picture = models.ImageField( "Profile picture", upload_to='profiles/', blank=True ) created_at = models.DateTimeField("Created at", auto_now=False, auto_now_add=True) updated_at = models.DateTimeField("Updated at", auto_now=True) def __str__(self): return f'{self.user} user profile' class Meta: verbose_name = 'User Profile' verbose_name_plural = 'User Profiles' What am I doing wrong? -
Elastic beanstalk won't process wsgi.py as a python module stating "No module named vine.five"
I'm trying to re-host a Django app on Elastic Beanstalk. It had been working find prior to mothballing it in August last year. After spinning it up I get a 500 error. The logs show this: Target WSGI script '/opt/python/current/app/app_name/wsgi.py' cannot be loaded as Python module. Exception occurred processing WSGI script '/opt/python/current/app/app_name/wsgi.py'. Traceback (most recent call last): File "/opt/python/current/app/app_name/wsgi.py", line 16, in <module> application = get_wsgi_application() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/opt/python/current/app/app_name/__init__.py", line 5, in <module> from .celery_settings import app as celery_app File "/opt/python/current/app/app_name/celery_settings.py", … -
Creating Evaluated Field in Django By Applying Aggregation 2 Fields
I am in phase of learning Django framework and I need some help to understand how to generate an evaluated field by summing up two inputs by user. I've used the code below where ops1 and ops2 will be provided by user and I need to show their sum in field total_ops at runtime. I've used the code below but that doesn't seems to work. class ManHour(models.Model): date = models.DateTimeField(auto_now=True) class Operations(models.Model): ops1 = models.DecimalField(max_digits= 5, decimal_places= 3) ops2 = models.DecimalField(max_digits= 5, decimal_places= 3) total_ops = Operations.ops1 + Operations.ops2 Error from code above TypeError: unsupported operand type(s) for +: 'DeferredAttribute' and 'DeferredAttribute'