Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploy React app in vercel with backend in render
Hi Everyone! Happy New Year I was trying to deploy my vite react application in vercel or netlify. I hosted it's backend part in render, Now backend is working, but when i hosted in frontend, the request URL change to hosted URL because I used vite proxy to use shortcut URL but it's not working in devlopment, Example of my vite cconfig // https://vitejs.dev/config/ export default defineConfig({ plugins: [ VitePWA(manifestForPlugin), react(), ], server: { proxy: { "/api": { target: "https://sample__.onrender.com", changeOrigin: true, secure: false, rewrite: (path) => path.replace("/api", ""), }, }, }, build: { proxy: { "/api": { target: "https://sample__.onrender.com/", changeOrigin: true, secure: false, rewrite: (path) => path.replace("/api", ""), } } } }); so when i call api my url is like: api/auth/login/ so in localhost, it will became, localhost:8000/auth/login/ but when i did it from dev server of netlify or vercel it become like vercel/netlify url/api/auth/login/ In localhost my backend is runnning in 8000 and frontend is runningin 5173 -
Django value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
i have a Django proj,I want to press button and date time save to db but error ,help please! view.py def confirm_order(request, pk): get_emp = get_object_or_404(Employee, pk=pk) if request.method == 'POST': new_end_date = request.POST['new_date'] get_emp.end_date = new_end_date get_emp.save() return redirect('all_emp') else: context = { 'get_emp': get_emp, } return render(request, 'confirm_order.html', context) ValidationError at /confirm_order/5/ ['“Feb. 29, 2023, 3:48 p.m.” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Request Method: POST Request URL: http://127.0.0.1:8001/confirm_order/5/ Django Version: 4.2.1 Exception Type: ValidationError Exception Value: ['“Feb. 29, 2023, 3:48 p.m.” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] Exception Location: /home/gino/PycharmProjects/office_emp_proj/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py, line 1567, in to_python Raised during: emp_app.views.confirm_order Python Executable: /home/gino/PycharmProjects/office_emp_proj/venv/bin/python Python Version: 3.10.12 Python Path: ['/home/gino/PycharmProjects/office_emp_proj', '/home/gino/PycharmProjects/office_emp_proj', '/snap/pycharm-professional/364/plugins/python/helpers/pycharm_display', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/gino/PycharmProjects/office_emp_proj/venv/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages', '/snap/pycharm-professional/364/plugins/python/helpers/pycharm_matplotlib_backend'] Server time: Mon, 01 Jan 2024 09:10:25 +0800 error_image ,how to resolve,Thanks i have a Django proj,I want to press button and date time save to db but error ,help please! -
How to deploy a remote production server using Jenkins?
We currently have our Dev server and Jenkins server on the same Cloud instance1. OS user: djDev Jenkins install owner: jenkins We are able to deploy our Django application build on this same instance1 using Jenkins and application is accessible fine but the files are deployed in /var/lib/jenkins folder. This is because Jenkins configuration is pointing to /var/lib/jenkins Is this possible to deploy the application in OS user folder, like /home/djDev/djApp While we try to modify the above folders and keep this instance1 for both Dev and Jenkins server, we need to deploy a production server on a remote cloud instance2 and deploy the application in a desired OS user´s using the same Jenkins server. (ex: user: djProd and /home/djProd/djApp) Our plan is to deploy the Production server as soon as automated tests are passed on Dev. server. Our repository is in Github. Please let me if there is any recommended steps to achieve the above deployment especially for Django application and also when users are different on each instance? Best Regards -
My React app isn't rendering the page right, it just shows a blank page
I'm following a YouTube video tutorial. I have the Django API setup and working. But I ran into an issue with the React frontend I can't figure out. React is rendering a blank white page when I run "npm start". Here's my Header.js: import React from 'react'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import Typography from '@material-ui/core/Typography'; import CssBaseline from '@material-ui/core/CssBaseline'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => ({ appBar: { borderBottom: `1px solid ${theme.palette.divider}`, }, })); function Header() { const classes = useStyles(); return ( <React.Fragment> <CssBaseline /> <AppBar position="static" color="white" elevation={0} className={classes.appBar} > <Toolbar> <Typography variant="h6" color="inherit" noWrap> BlogmeUp </Typography> </Toolbar> </AppBar> </React.Fragment> ); } export default Header; Here's my App.js: import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App; And here's my index.js: import React from 'react'; import ReactDOM from 'react-dom'; import * as serviceWorker from './serviceWorker'; import './index.css'; import { Route, BrowserRouter as Router, Switch } from 'react-router-dom'; // import { Route, BrowserRouter as … -
Django admin panel css not showing
Django css files not loading in admin panel I created a new project pro-a And I start a new app core Than I migrate and made superuser And open localhost:8000/admin Everything is ok I didn't change or update anything enter image description here Admin panel I also reinstall django -
Is there a way to define multiple actions in django model admin, without specifying their number?
i have 3 models: Team, TeamDetail and Sheet. in SheetModelAdmin, I want to have as many actions as my teams. And it is not known how many teams I will have. Is there a way to solve this? The following code only adds the first team actions = list() teams = Team.objects.filter() if teams: for team in teams: actions.append('add_team_to_attendance') @admin.action(description=f"Add team {team.name} to selected attendance") def add_team_to_attendance(self, request, queryset, team=team): team_details = TeamDetail.objects.filter(team=team) for td in team_details: for query in queryset: AttendanceDetail.objects.create(attendane=query, player=td.player) -
Django 5 and Python 3.12.1 send_mail fails with SSL error
I have a working application using Django 3.2.6 and Python 3.9.6. I'm trying to upgrade to Django 5 and Python 3.12.1. So far, I've managed to track down and fix a number of problems caused by various changes and deprecations but this one has had me stumped for several days. Using Django send_mail() in the new environment fails with ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: IP address mismatch, certificate is not valid for '40.99.213.34'. (_ssl.c:1000). Here's a code extract: settings.py EMAIL_HOST = socket.gethostbyname('smtp.office365.com') # resolves IPV4 address EMAIL_PORT = 587 EMAIL_HOST_USER = 'name@company.co.uk' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True views.py send_mail('Subject','Message Body','name@company.co.uk',['name@gmail.com']) If I add the following line to my settings (gleaned from SO after hours of searching), the error changes to something even less helpful: [SSL] PEM Lib (_ssl.c:3917) import certifi EMAIL_SSL_CERTFILE = certifi.where() It seems clear that something has changed in the way ssl connects, maybe it's insisting on verifying certs in a different way than it did in Python 3.9.6. I've spent many hours fruitlessly searching for a solution. I've looked at the source for the django smtp module and the python ssl module and in desperation even the cpython _ssl module, but I can't figure out … -
Issue in email login with customUser in Django rest framework
i'm working on a school projet , and i basically have an issue with the login i canot make it work no matter how many overrding im doing it always show me that my query doesnt match any existing user ( whe its the correct email/password combination ) custom user model : class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("email address"), unique=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) is_company = models.BooleanField(blank=True,null=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email custom email backend: class EmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = UserModel.objects.get(Q(email__iexact=username)) except UserModel.DoesNotExist: UserModel().set_password(password) except MultipleObjectsReturned: return CustomUser.objects.filter(email=username).order_by('id').first() else: if user.check_password(password) and self.user_can_authenticate(user): return user def get_user(self, user_id): try: user = UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None return user if self.user_can_authenticate(user) else None login view class LoginAPIView(APIView): def post(self,request): serializer = LoginSerializer(data = request.data) if serializer.is_valid(): email = serializer.validated_data["email"] password = serializer.validated_data["password"] user = authenticate(request, username=email, password=password) if user is not None: #We are reterving the token for authenticated user. token = Token.objects.get(user=user) response = { "status": status.HTTP_200_OK, "message": "success", "data": { "Token" : token.key } } return Response(response, status = status.HTTP_200_OK) else : response = { "status": status.HTTP_401_UNAUTHORIZED, "message": "Invalid Email … -
Python Django - Not able to download video completely in the client's machine using FileResponse
I'm building a video downloader using Django. I have the url from where the video is played. Inside the download view, first, I'm sending a request using requests library to that url with stream=True and storing the response in a res variable. And finally, I'm returning the a FileResponse with the res and 'Content-Disposition' = 'attachment; filename="downloaded_video.mp4"' and with content length. def download(request): url = "https://rr-rkf.com/lkdlfj8eijkjjoifu99ooijLKJr8goijoijrg0j94" res = requests.get(url, stream=True) content_length = res.headers.get('Content-Length') content_type = 'video/mp4' file_response = FileResponse(res, content_type = content_type) file_response['Content-Disposition'] = 'attachment; filename="download_video.mp4"' file_response['Content-Length'] = content_length url_patterns url_patterns = [ path('/download', views.download, name='download') ] When I go \download, the video started downloading and struck after downloading some bytes. In the browser it shows resuming for long time but there is no progress. But in the terminal, I got this error Traceback (most recent call last): File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\urllib3\response.py", line 712, in _error_catcher yield File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\urllib3\response.py", line 833, in _raw_read raise IncompleteRead(self._fp_bytes_read, self.length_remaining) urllib3.exceptions.IncompleteRead: IncompleteRead(212992 bytes read, 614518 more expected) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\requests\models.py", line 816, in generate yield from self.raw.stream(chunk_size, decode_content=True) File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\urllib3\response.py", line 934, in stream data = self.read(amt=amt, decode_content=decode_content) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\USER\OneDrive\Documents\DownloaderWebDjango\env\Lib\site-packages\urllib3\response.py", … -
Unsaved model instances to related filters in tests for django 5.0
In Django 5 "passing unsaved model instances to related filters is no longer allowed" (https://docs.djangoproject.com/en/5.0/releases/5.0/). Basically before I had this method (only relevant code shown): def make_payload(user, nonce, exclude_groups=None): exclude_groups = set(exclude_groups or []) relevant_groups = Group.objects.filter(internal_only=False).order_by("internal_name") filter_q = Q(user=user) & ~Q(pk__in=exclude_groups) add_groups = relevant_groups.filter(filter_q).values_list("internal_name", flat=True) ... And tested it using this test method (only relevant code shown): def test_builds_payload_not_activated(self): user = accounts.tests.factories.UserFactory.build(email_verified=False) payload = utils.make_payload(user, "nonce-nce") ... Now obviously the instance as not been saved as it's a unit and not an integration test. This leads to relevant_groups.filter(filter_q) failing with ValueError: Model instances passed to related filters must be saved. Basically I've no idea how to fix the test as the code is still working in a real environment. Ideas welcome. -
Django MultiSelectField Error: 'super' object has no attribute '_get_flatchoices'
I tried to use Django Multiselectfield library but i got this error: I already installed it properly by command: pip install django-multiselectfield I also added in my settings.py INSTALLED_APPS = [ ..... 'multiselectfield', ] My models.py: from multiselectfield import MultiSelectField from django.db import models CATEGORY = [ ('CP', 'Computer Programming'), ('LG', 'Language'), ('MA', 'Mathematics'), ('BM', 'Business Management'), ('GK', 'General Knowledge') ] class Quiz(models.Model): ... title = models.CharField(max_length=256) category = MultiSelectField(choices=CATEGORY, max_choices=2, max_length=5) ... def save(self, *args, **kwargs): if not self.category: self.category = ['GK'] super(Quiz, self).save(*args, **kwargs) def __str__(self): return self.title The error: 'super' object has no attribute '_get_flatchoices' However this is located in the Multiselectfield library code. Because of this error, even my data cannot be saved. I tried to find out what am I missing, but I have no idea. Any idea what's wrong with my code? Appreciate your help ^_^ -
Integrate webpack template with Django
I'm working on a Django project, and I'm trying to integrate an HTML template built with npm using webpack into the Django project. I'm curious about the necessity of these {% static %} tags in the HTML templates. Issue: When visiting a URL like /view/user, static files are being loaded from /view/user instead of the expected /static. This happens because I am not adding the {% static %} template tag in the html templates. Question: Is there is a Django setting in order to avoid adding the {% static %} template tag to each line and save time? Has anyone encountered this problem before? settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'events_core/frontend/dist')], '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', ], }, }, ] STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'events_core/frontend/dist'), ] -
I get the following error while registrating: "The view account_module.views.view didn't return an HttpResponse object. It returned None instead"
I used HttpResponseRedirect and redirect but didn't work: your text class RegisterView(View): def get(self, request): registration_form = RegisterForm() context = {"registration_form": registration_form} return render(request, "account_module/registration.html", context) def post(self, request): registration_form = RegisterForm(request.POST) if registration_form.is_valid(): user_email = registration_form.cleaned_data.get("email") user = User.objects.filter(email__iexact=user_email).exists() if user: registration_form.add_error("email", "This email is already taken") else: new_user = registration_form.save(commit=False) new_user.is_active = False new_user.save() # Todo send_email return redirect(reverse("login")) # return HttpResponseRedirect(reverse_lazy("login")) context = {"registration_form": registration_form} return render(request, "account_module/registration.html", context) this is urls.py: your text from django.urls import path from . import views urlpatterns = [ path("registration/", views.RegisterView.as_view(), name="register"), path("login/", views.LoginView.as_view(), name="login"), ] -
Why am I having a key error on my target column and a value error that says; A given column is not a column of the dataframe
# firstly, I split my data target = 'member_casual' X_train = train.drop(target, axis=1) y_train = train[target] # Then, transformed my numerical and categorical columns cat_trans = Pipeline([("imputer", SimpleImputer(strategy="most_frequent")),('encoder',OneHotEncoder(handle_unknown="ignore", drop="first", sparse=False))]) num_trans = Pipeline([("imputer", SimpleImputer(strategy="mean")),("scaler", MinMaxScaler())]) preprocessor = ColumnTransformer(transformers=[('num', num_trans, num),('cat', cat_trans, cat)]) pipeline = Pipeline([('preprocessor', preprocessor)]) # then this next code gave me errors pipe_fit = pipeline.fit(x_train) A key error and value error: A given column is not a column of the dataframe -
Dont understand the message
I'm currently following this tutorial: https://www.youtube.com/watch?v=8jazNUpO3lQ&list=PLeo1K3hjS3uvCeTYTeyfe0-rN5r8zn9rw&index=2 That's the code from tutorial reg = linear_model.LinearRegression() reg.fit(df[['area']],df.price) --LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False) After writing this specific code, That's my code reg = linear_model.LinearRegression() reg.fit(df[['Area']],df.Price) --LinearRegression() # Its not showing same as the tutorial code reg.predict([[3300]]) # after running this code its showing the below message and also giving the output D:\New folder\anaconda\lib\site-packages\sklearn\base.py:450: UserWarning: X does not have valid feature names, but LinearRegression was fitted with feature names warnings.warn( array([628715.75342466]) Why is my code not showing same out as tutorial --LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False) And what is the meaning of this message D:\New folder\anaconda\lib\site-packages\sklearn\base.py:450: UserWarning: X does not have valid feature names, but LinearRegression was fitted with feature names warnings.warn( -
MYSQL drive issue when Django app run on Azure Function
When running Django app on Azure function, Im getting below error. "ENGINE": "django.db.backends.mysql" Result: Failure Exception: NameError: name '_mysql' is not defined Stack: Is there any solution for this issue ? Assuming cant install mysql module on Azure function. -
Pycharm theme colors not changing from color scheme
PROBLEM Hi, I'm new to PyCharm, but used to Atom with a bunch of plugins as my IDE for Django, etc (switching cause no more Atom support, and it has bugs). I applied a theme I like well enough, duplicated it, and went to Settings > Editor > Color Scheme to change the colors of parts I don't like in ... > Color Scheme > Python For the most part, it's fine. It shows that both binary (bytes) and Text (unicode) strings are green, as I want. And they are fine when writing a function, doc string, etc: But when I'm in urls.py, the url routes aren't green like the other strings: WHAT I ALSO TRIED I checked the color schemes for Django, but it only has default colors for the template language only. Same thing in the HTML section for Attribute value (for href, src, etc values) Same for their inheritance at ... Language defaults > String > String text. I can add any other function in urls.py, call it anywhere, and it'll show the proper green (see url routing above), but not for path(). QUESTION Any ideas where / how to make it green? What have I missed? … -
python manage.py runserver not running proper
I am currently working in a Django project. I am running it through Docker, but I want to run it manually. I keep getting messages of error after run "python manage.py runserver" and it does perfoming system checks, I am stuck on this. Log: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\camil\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\camil\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\management\base.py", line 387, in check all_issues = self._run_checks( ^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\management\base.py", line 377, in run_checks return checks.run_checks(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() ^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\urls\resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File " C:\Users\camil\Downloads\site\venv\Lib\site-packages\django\urls\resolvers.py", … -
Django error migrating nesting model w/o migrating base model
Purpose to have one BaseModel that can be nested by other models NOTE: BaseModel should not be written to database So I have one BaseModel like below class StaticVariable(models.Model): class Meta: managed = False title = models.CharField( max_length=250, blank=False, null=False ) alias = models.CharField( max_length=250, blank=False, null=False, unique=True ) created_at = models.DateTimeField( auto_now_add=True, blank=False, null=False ) updated_at = models.DateTimeField( auto_now=True, blank=False, null=False ) enabled = models.BooleanField( default=True, blank=False, null=False ) deleted = models.BooleanField( default=False, blank=False, null=False ) I made migrations and applied it, since class Meta has managed=False parameter, actual sql table is not being created (as expected) After that I craete new model wich is being nested from StaticVariable model as base class BodyType(StaticVariable): class Meta: db_table = 'body_type' ordering = ["title", "-id"] Then I makemigrations, which looks like this from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('utils', '0004_staticvariable'), ('app', '0002_alter_category_enabled'), ] operations = [ migrations.CreateModel( name='BodyType', fields=[ ('staticvariable_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='utils.staticvariable')), ], options={ 'db_table': 'body_type', 'ordering': ['title', '-id'], }, bases=('utils.staticvariable',), ), ] But, unexpectedly I catch below error when I try to migrate Running migrations: Applying app.0003_bodytype...Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 87, in _execute return self.cursor.execute(sql) File … -
Vues generic DeleteView : accès à la clé
Salut à toutes et à tous, j'espère vous savoir en bonne santé et je vous adresse mes vœux pour le nouvel an par anticipation. J'ai une liste d'enseignant que j'affiche avec trois boutons:Voir, Modifier et Supprimer. Ce dernier ouvre une fenêtre modale qui demande confirmation de suppression: Voulez-vous supprimer {{nom et prénom}} de la personne. Le problème c'est qu'à chaque itération de la boucle {% for %} C'est toujours le nom du premier enseignant récupéré par l'objet de contexte qui s'affiche. Je suis convaincu que le problème vient de la fenêtre modale car quand je la retire, tout fonctionne correctement. Comment faire pour résoudre ce problème ? Merci d'avance -
Troubleshooting AWS Elastic Beanstalk Deployment Errors with Django Applications - Error: EbExtension build failed
When I was trying to deploy my Django application to AWS Elastic Beanstalk. Then I got this error. 2023/12/30 21:26:42.478526 [ERROR] An error occurred during the execution of command [app-deploy] - [PreBuildEbExtension]. Stop running the command. Error: EbExtension build failed. Please refer to /var/log/cfn-init.log for more details. What is the reason for that? Here is my Django.config which is located in .ebextensions folder. When I remove the 'commands' it gives me 502 bad gateway since the application cannot import the relavant packages. commands: 01_activate_virtualenv: command: "source /var/app/venv/staging-LQM1lest/bin/activate" 02_install_requirements: command: "pip install -r /var/app/current/requirements.txt" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: django-pixel/core/wsgi.py -
Django URL Pattern Results in 404 Not Found Error stripe succeed
I'm working on a Django project with a payment processing feature and encountering a "404 Not Found" error when making a request to a specific URL. I've set up my URL patterns and views, but the request to /dashboard/services/payment/success/ is not being found. On the platform of stripe the payments are successful and I receive a confirmation in the console log. Here's the relevant code and error log: [30/Dec/2023 21:33:10] "POST /dashboard/services/payment/success/ HTTP/1.1" 404 4949 Error notifying backend:"Request failed with status code 404" urlpatterns = [ # ... other URL patterns ... path('payment/', views.make_payment, name='make_payment'), path('payment/success/', views.payment_success, name='payment_success'), path('payment/success_page/', views.payment_succeed, name='payment_succeed'), ] @login_required def make_payment(request): if not request.user.is_client: messages.error(request, "Only clients can make payments.") return redirect('services:dashboard') diagnostic_requests = DiagnosticRequest.objects.filter(client=request.user, payments__isnull=True) if not diagnostic_requests.exists(): messages.info(request, "You have no unpaid diagnostic requests.") return redirect('services:dashboard') total_cost = diagnostic_requests.aggregate(Sum('service__cost'))['service__cost__sum'] if request.method == 'POST': if request.headers.get('X-Requested-With') == 'XMLHttpRequest': # Initialize Stripe API stripe.api_key = settings.STRIPE_SECRET_KEY # Create a Stripe Payment Intent intent = stripe.PaymentIntent.create( amount=int(total_cost * 100), # Convert to cents currency='usd', payment_method_types=['card'] ) # Return the client secret in a JSON response return JsonResponse({'client_secret': intent.client_secret}) # Create a Payment record payment = Payment.objects.create( user=request.user, stripe_payment_intent_id=intent.id, paid_amount=total_cost, currency='USD' ) # Link payment with all diagnostic … -
Combining two databases together for seamless login
I have 2 applications developed with two different frameworks. One is using pure PHP and the other using Python Django. My question is related to database combination for seamless login. How does one even begin to have the following scenario? User is created on python application with email and password. User should be able to seamlessly login with credentials from one database to the other PHP application If user wants to login directly onto PHP application, they can do that as well. How would something like this be accomplished? I tried a couple of options of combining webhooks, but do not have enough knowledge of this to even understand. -
TypeError: Cannot combine queries on two different base models
In my django project i have 3 app, agent, teamlead, and phone. Both teamleaders models and agents models are of type FieldOfficer. A FieldOfficer has a phone. And since these phones are rotated, ie chances of a phone belonging to many FieldOfficers and viceversa are high. The FieldOfficer class is an abstract one and housed inside a python package separately. Now my problems start when i try to make a ModelForm from the Phone model. I keep getting a "TypeError: Cannot combine queries on two different base models." type here FieldOfficer Abstract Class from django.db import models class FieldOfficer(models.Model): first_name = models.CharField(max_length = 30, blank=False, null=False) last_name = models.CharField(max_length = 30, blank=False, null=False) personal_phone_number = models.CharField(max_length=30, unique=True, blank=False, null=False) alternative_phone_number = models.CharField(max_length=30, unique=True, blank=False, null=False) region = models.CharField(max_length=30) class Meta: abstract = True agent.models.py class Agent(FieldOfficer): teamleader = models.ForeignKey('teamleader.TeamLeader', null=True, on_delete=models.SET_NULL, related_name='teamlead') def __str__(self): return f'{self.first_name} {self.last_name}' teamlead.models.py class TeamLeader(FieldOfficer): def __str__(self): return f'{self.first_name} {self.last_name}' phone.Models.py class Phone(models.Model): field_officers = models.ManyToManyField(FieldOfficer, through='AgentPhoneAssignment', related_name="phone") def __str__(self): return f'{self.name} {self.imei}' class AgentPhoneAssignment(models.Model): field_officer = models.ForeignKey(FieldOfficer, on_delete=models.SET_NULL) phone = models.ForeignKey(Phone, on_delete=models.SET_NULL) ... # other fields def __str__(self): return f'{self.field_officer} {self.phone}' Create Phone form Class class CreatePhoneForm(forms.ModelForm): class Meta: model = Phone fields = … -
`UNIQUE constraint failed at: pharmcare_patient.id` in my pharmcare app
I have a Django app in my project I am currently working on called pharmcare, and I kind of getting into a unique constraint issue whenever I want to override the save() method to insert/save the total payment made by the patient so that the pharmacist that is creating the form or updating the patient's record won't perform the math manually. Whenever I used the form from CreateView on the view.py without overriding the save method with the function I created dynamically to solve the math, it performed the work perfectly well, but in the admin panel, the answer wouldn't appear there. However, if I tried using the save() in my models.py of the app I'd get that error. If I remove the save() method in the model, the error will disappear, and that's not what I want, since I want it to be save in the db immediately the pharmacists finished creating or modifying the form. I had used the get_or_create method to solve it but it remains abortive, and another option which I don't want to use (since I want the site owner to have the option of deleting the pharmacist/organizer creating the record at ease same with …