Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Show the child Query in admin-panel of Django
I have different variation in attribute model by tabularinline: class Attribute(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(null=True, blank=True) def __str__(self): return self.title class Variations(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(null=True, blank=True) image = models.ImageField(upload_to='variations', null=True, blank=True) attribute = models.ForeignKey(Attribute, null=True, on_delete=models.SET_NULL, related_name='variation') def __str__(self): return self.title now I made a relationship Product model with Attribute: class Product(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=250, unique=True) description = RichTextUploadingField(null=True) short_description = RichTextUploadingField(null=True) regular_price = models.IntegerField() sale_price = models.IntegerField(null=True, blank=True) sku = models.CharField(max_length=200, null=True, blank=True) dimenstions = models.CharField(max_length=200, null=True, blank=True) stock_quantity = models.IntegerField(default=0) category = models.ManyToManyField(Category, related_name='category') tag = models.ManyToManyField(Tags, related_name='tag') attributes = models.ManyToManyField(Attribute, through='ProductVariation', related_name='products') image = models.ImageField(upload_to='shop/image', null=True, blank=True) # tax_class = pass # shiping_class = pass # related_product = pass # variation = pass def __str__(self): return self.title def thumbnail_tag(self): return format_html( "<img width=100 height=75 style='border-radius: 5px;' src='{}'>".format(self.image.url)) thumbnail_tag.short_description = "Thumbnail" class ProductVariation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) def __str__(self): return f"{self.product} - {self.attribute_value}" Now I want when users choose attribute 1 to show them in another field all the variations of that attribute and do this for different attributes with different variations. For example when I want to … -
Django REST: Get pk of model object in create context
I am in the middle of a project where I am creating a scheduling system for courses. Courses may have a number of sessions. I would like, upon course creation, to create a number of blank sessions (to be scheduled later) equal to a variable in the course request ("class_count"). Each Session has FKs to the user profile and course. The logic I have is something like this: serializer.save(instructor=self.request.user) for sess in range(int(request.POST.get('class_count'))): Session.objects.create(user=self.request.user.profile, session_active=True, course=request) Session.save() However, when I do this, I get this error: ValueError: Cannot assign "<rest_framework.request.Request: POST '/create/'>": "Session.course" must be a "MyCourse" instance. How would I access the instance of the MyCourse model just created? -
How to filter queryset by decimal stored in JSON?
I store some decimal's string representation in JSONField and want to filter by it. Here's the model: class Asset: cached_data = JSONField() Content of JSONFields: { "price": "123.456" } I tried a lot of ways to filter queryset by this value. The last one was Asset.objects.annotate('price_as_decimal': Cast('cached_data__price', output_field=DecimalField())).filter(price_as_decimal__gt=100) but it gives the error: django.db.utils.DataError: invalid input syntax for type integer: "none" while I'm sure there's a value for this key in the field -
django unable to implement decorator_from_middleware functionality
I am working on a project where I am trying to write a middleware which when called will verify token from a third party service and check roles stored in that token. I am able to write and use middleware successfully, but I need to implement it for selected views only, for which I am unable to convert the middleware to decorator using decorator_from_middleware to use only where it is required. This is the middleware class (with token verification part removed). class SimpleMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. print(f"inside the custom middleware") response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response This is how I am trying to use it in a view file. from django.utils.decorators import decorator_from_middleware from users.middleware import SimpleMiddleware simple_decorator = decorator_from_middleware(SimpleMiddleware) class UserPoolInfo(APIView): @simple_decorator def get(self, request): user_manager_object = UserManager() user_pool_info = user_manager_object.get_user_pool_info() response_data = { "status":"Success", "statusCode": status.HTTP_200_OK, "message":"fetched user pool information", "data": user_pool_info } return Response(response_data, status.HTTP_200_OK) we are using Django 5.0 with Django Rest Framework. I have tried following answer from this … -
Validation of min and max doesn't work for custom widgets of django
I use a custom widget to show addon through the input-group of Bootstrap. It is shown but min-value and max-value operation don't work correctly and their message doesn't display. class PrependWidget(Widget): def __init__(self, base_widget, data, *args, **kwargs): u"""Initialise widget and get base instance""" super(PrependWidget, self).__init__(*args, **kwargs) self.base_widget = base_widget(*args, **kwargs) self.data = data def render(self, name, value, attrs=None, renderer=None): u"""Render base widget and add bootstrap spans""" field = self.base_widget.render(name, value, attrs) return mark_safe(( u'<div class="input-group mb-3">' u' <div class="input-group-prepend">' u' <span class="input-group-text" id="addon_{name}" value="{value}">%(data)s</span>' u' </div>' u'<input type="text" class="form-control" id="id_{name}" name="{name}" {attrs} ' u'aria-describedby="addon_{name}"> ' u'</div>'.format(name=name, value=value, attrs=attrs or '') ) % {'field': field, 'data': self.data}) hard = forms.IntegerField(min_value=0, max_value=20, required=False, widget=PrependWidget(base_widget=forms.NumberInput, data='GB')) -
how to send mail using godaddy cpanel mail in django
I created an email on godaddy c-panel hosting . I have written some codes in Django to send mail using this mail and in recipients mail I have 3 mails and one is c-panel email. It is sending mail to only c-panel mail not to others two. Also I have configured DNS and forwarder but that's also not working. -
Can't quite figure out this DRF endpoint
I am working on this endpoint to store an email. I send a POST to /emails with { "email": "user101c@email.com" } and get an error IntegrityError at /emails (1048, "Column 'user_id' cannot be null"). Clearly, this is a database level error. The user_id field shouldn't be set by the user. I'm not sure how to proceed. models.py class EmailAddress(ExportModelOperationsMixin('email_address'), models.Model): user = models.ForeignKey(User, related_name='emails', on_delete=models.CASCADE) email = models.EmailField(max_length=255) verify_key = models.CharField(max_length=255, null=True, blank=True) verified = models.BooleanField(default=False) created = models.DateTimeField(auto_now=True) verification_sent = models.DateTimeField(null=True, blank=True) reset_key = models.CharField(default=None, null=True, max_length=255, blank=True) reset_sent = models.DateTimeField(null=True, blank=True) class Meta: verbose_name = _("email") verbose_name_plural = _("emails") unique_together = [("user", "email")] ordering = ['-created'] def __str__(self): return self.email def save(self, *args, **kwargs): self.verify_key = get_random_string(length=32) if not self.id: # if new verify_email_signal.send(sender=self.__class__, email=self.email, key=self.verify_key) self.verification_sent = timezone.now() super(EmailAddress, self).save(*args, **kwargs) serializers.py class EmailAddressSerializer(serializers.ModelSerializer): class Meta: model = account_models.EmailAddress fields = ['user', 'email', 'verified', 'created', 'verification_sent', 'reset_sent'] read_only_fields = ['id', 'user'] views.py class EmailAddressViewSet(ModelViewSet): permission_classes = (permissions.IsAuthenticated,) serializer_class = serializers.EmailAddressSerializer def get_queryset(self): return account_models.EmailAddress.objects.filter(user=self.request.user) urls.py email_list = views.EmailAddressViewSet.as_view({ 'get': 'list', 'post': 'create' }) email_detail = views.EmailAddressViewSet.as_view({ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }) urlpatterns = [ path('emails/', email_list, name='email_list'), path('emails/<int:pk>/', email_detail, name='email_detail'), ] -
Stripe Checkout Session Django Subscription
I'm not a developer or software engineer. We've put together almost the entirety of a web app with the help of chatgpt. It's worked great up to this point... I would like to do the following: Implement payments on my website through Stripe Use the Stripe Checkout Session Use the ui_mode = embedded option. I would like an embedded form not a redirect away from our website to Stripe's Must use python django framework The Stripe documentation has a guide that I'm sure is great for a flask app but I am really struggling to adapt it to django. https://stripe.com/docs/checkout/embedded/quickstart?lang=python Would any be able to help translate the flask documentation to a django framework? -
Django not sending messages despite correct implementation
Specs: Django version 4.2.5, Python 3.11, Visual Studio Code. I use (well, attempting to use) SendGrid to send a web form & I'm currently in development (DEBUG = True). Having followed the QuickStart tutorial supplied by SendGrid, I can confirm that the SG has been installed correctly, including the .env which houses the SENDGRID_API_KEY I have also followed the following documentation to the letter: Sendgrid Django documentation I am completely stumped as to how the developers of SendGrid can justify pushing this content into the public domain because I have not seen one iota of evidence that the API is fully operable. Also, I am following this tutorial: Codemy tutorial This is my code: {% if message_name %} <center> <h1>Thanks {{message_name}}!</h1> <p>We will get back to you shortly.</p> {% else % } <section class="vp"> <div class="parent parent--headline"> <form method="POST" action="{% url 'careers' %}"> {% csrf_token %} <input required type="text" name="message-name" placeholder="First name"/><br/><br/> <input required type="email" name="message-email" placeholder="Email"/><br/><br/> <textarea required spellcheck="true" name="message" placeholder="Insert your message"></textarea> <input type="submit" value="Send feedback" class="btn btn--pink"/> </form> </div> </section> </center> {% endif %} In the settings.py, I have the following: SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY') EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' # this is exactly the value 'apikey' … -
Django CREATING databases dynamically at runtime( NOT ROUTING the requests to right DB)
how does one go about creating a new database for each tenant at run time dynamically. All the examples are hard coded into settingsfile. But when a new tenant,t1, registers, I would like to create a new database for t1. and when a t2 connects I would like to be able to create that t2_db at runtime which out running any migrations or server restart. So let say we have a default db where we do our migrations,(empty) we just copy that for t1 and t2. Or is there a way to run migrations with out restarting the server. Or do people just restart the server(crazy right) If not I am thinking docker. Thanks -
Cookie set not working with django and next js app hosted on azure and confiured to use custom domain
I have two applications. A next.js frontend app and a Django backend app. The backend uses Django's session storage and I'm trying to set cookies in the browser. This was working on localhost. I'm using Azure to host my application. I bought my own domain called something.xyz. I put my frontend as an A record with host as @ in my DNS configuration and my backend as a CNAME with host as ser. There are also TXT records for azure config. When I go to ser.something.xyz I can access my backend. I can also access my frontend when I go to something.xyz. I have set both SESSION_COOKIE_SAMESITE and CSRF_COOKIE_SAMESITE to None. I have set both SESSION_COOKIE_DOMAIN and CSRF_COOKIE_DOMAIN to either something.xyz, .something.xyz, or ser.something.xyz. I also tried putting https:// in front (that's probably wrong but I'm desperate) I know this question has been asked before, but I just can't seem to get it to work. I have changed my settings several times This is the message I'm getting from the network tab: csrftoken=xxxxxxxxxxxxxxxx; Domain=['something.xyz']; expires=Mon, 03 Feb 2025 22:41:48 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure this attempt to set a cookie via a Set-cookie header was blocked because its domain attribute … -
"How do I add styles to html_body in Django with win32?"
I am trying to send emails through Django using the win32 library, but the HTML styles are not being applied. The styles in the head work sporadically, and the styles in the body also work sporadically ` pythoncom.CoInitialize() dynamic_link='prueba' try: # Obtén todos los ingenieros con sus nombres concatenados outlook = win32.Dispatch('Outlook.Application') mail = outlook.CreateItem(0) # Configurar el remitente mail.SentOnBehalfOfName = 'example@outlook.com' mail.To = adminEmail mail.Subject = 'NUEVA SOLICITUD DE PRUEBAS DE LABORATORIO' html_body = f""" <html> <head> <style> body {{ font-family: Arial, sans-serif; padding: 20px; }} h1, p {{ color: #333; }} .background-red {{ background-color: red; }} #button {{ display: inline-block; padding: 10px 20px; background-color: #4CAF50; color: #fff; text-decoration: none; border-radius: 5px; }} </style> </head> <body class="background-red"> <h1>Solicitud de pruebas de laboratorio</h1> <p>Nueva solicitud pruebas de laboratorio del usuario {FullName}</p> <div style="width: 130px; height:130px; background-color:white;"> <p>El usuario {FullName} ha creado una nueva solicitud de pruebas de laboratorio para el cliente {customer} con una fecha requerida para el {require_date}</p> </div> <a href="{dynamic_link}" id="button">Ir a la página</a> </body> </html> """ mail.HTMLBody = html_body mail.Send() return Response({"message": "Correo enviado correctamente"}, status=status.HTTP_200_OK) except Exception as e: print(f"Error: {e}") finally: # Liberar recursos pythoncom.CoUninitialize()` I need help please, i'am new in django -
Python Django in Docker - Input device error
I've tried to deploy my Django App on DigitalOcean App Platform. Due to using PyAudio I had to use Dockerfile, because python3-pyaudio requires "apt-get". I've created Dockerfile and successfull installed PyAudio. Unfortunetly I've got an error "OSError: No Default Input Device Available". [speech-to-text] [2024-02-05 22:42:35] /usr/local/lib/python3.10/site-packages/pydub/utils.py:170: RuntimeWarning: Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work [speech-to-text] [2024-02-05 22:42:35] warn("Couldn't find ffmpeg or avconv - defaulting to ffmpeg, but may not work", RuntimeWarning) [speech-to-text] [2024-02-05 22:42:35] Not Found: / [speech-to-text] [2024-02-05 22:42:40] ALSA lib confmisc.c:855:(parse_card) cannot find card '0' [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5180:(_snd_config_evaluate) function snd_func_card_inum returned error: No such file or directory [speech-to-text] [2024-02-05 22:42:40] ALSA lib confmisc.c:422:(snd_func_concat) error evaluating strings [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5180:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory [speech-to-text] [2024-02-05 22:42:40] ALSA lib confmisc.c:1334:(snd_func_refer) error evaluating name [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5180:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5703:(snd_config_expand) Evaluate error: No such file or directory [speech-to-text] [2024-02-05 22:42:40] ALSA lib pcm.c:2666:(snd_pcm_open_noupdate) Unknown PCM sysdefault [speech-to-text] [2024-02-05 22:42:40] ALSA lib confmisc.c:855:(parse_card) cannot find card '0' [speech-to-text] [2024-02-05 22:42:40] ALSA lib conf.c:5180:(_snd_config_evaluate) function snd_func_card_inum returned error: No such … -
How to test a function of view in Django
I am learning basics of Django following official tutorial and adding some new features to my application. So I added a view that can nullify all votes of particular question def nullask(request, question_id): question=get_object_or_404(Question, pk = question_id) if request.method == "GET": return render(request, "polls/nullifyask.html", {"question":question}) else: for i in question.choice_set.all(): i.votes = 0 i.save() return HttpResponseRedirect(reverse("polls:index")) So it works fine, but I wanted to practice in writing tests and wanted to write a test that test that votes are really nullified. Here it is class NullingViewTest(TestCase): def test_nulling(self): q=create_question(text="Future", days=-1) choice=q.choice_set.create(choice_text="1", votes=10) response=self.client.post(reverse('polls:nullask', args=(q.id,))) self.assertEqual(choice.votes, 0) It does't work(votes are not changing from 10 to 0 and AssertionError: 10 != 0 appears. I understand why this happens but cannot make it work like I want. What should I do here is nullify ask.html: <!doctype html> <html lang="en-US"> <head> <meta charset="utf-8" /> <title>Nullyfying of {{question_id}}</title> </head> <body> <form method="post"> {% csrf_token %} <legend><h1>Do you want to nullify votes of question {{question.text}}</h1></legend> <input type="submit" name="Yes" value="Yes!"> </form> </body> </html> Here are models: class Question(models.Model): text=models.CharField(max_length=200) productiondate=models.DateTimeField("date published") def was_published_recently(self): return self.productiondate >= timezone.now() - datetime.timedelta(days=1) and self.productiondate<timezone.now() def __str__(self): return self.text class Meta: permissions=(("can_nullify","User can nullify votes" ),) class Choice(models.Model): question = … -
Configuration files error after trying to deploy a Django App on AWS Elastic Beanstalk
I have a simple (no database) website made with Django that i'm trying to deploy on AWS Elastic Beanstalk. I got a WARN error : "Configuration files cannot be extracted from the application version toulouse-psy-emdr-v2. Check that the application version is a valid zip or war file." I don't find any explanation about it. I followed a tutorial for the .ebextensions file, my zip file is valid. The rest is successful. The application doesn't work and I get a 502 Bad Gateway error. I found people talking about it, but no clear solution. Does anybody have ever had that error ? What can I do ? I ckecked my .ebextensions file and the django.config inside. It looks like this : option_settings: aws:elasticbeanstalk:container:python: WSGIPath: cabinet_psycho.wsgi:application -
Django test fails to create correct test DB, even main DB works fine
I have app "Invoice" with two models "Invoice" and "InvoicePDFTemplate". I wanted to add fields "terms" on both of them. With model Invoice everything went good, but I have problems with PDFTemplates: makemigrations and migrate worked fine - new column was created in DB, I successfully developed code needed. but when i ran test invoice - it failed as it seems that tests DB does not apply correctly migrations: Using existing test database for alias 'default'... Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column invoice_invoicepdftemplate.terms does not exist LINE 1: ...fault", "invoice_invoicepdftemplate"."is_active", "invoice_i... I've tried to change fields, delete migrations and recreate it. It does not solve the problem. I cannot understand why one model works fine and other does not. And I cannot skip test as it is a part of CI/CD. could you suggest any solution? -
I have created an html form but I want to make my website automatically create a dashboard from the inputted data from the form [closed]
Please how someone should kindly help me with the source code I've created the html form and need to create a dashboard from the inputted data from the form I would be so grateful if someone could put me through and send the source code -
Django time data '2024-02-15' does not match format '%Y/%m/%d '
I'm having problems to strip a date: pFecha = datetime.strptime(pFechaDesde, '%Y/%m/%d') Where: pFechaDesde = '2024-02-15' The date was got from a input type date Thanks. -
Getting 403 error when sending a POST request Angular
I am getting status code 403 error when sending post requset to server in django, the server is runing on locallhost, in postman the post request is working, What is the reason of occuring error My auth.service.ts file getUser():Observable<any>{ const token = localStorage.getItem('jwt'); if(!token){ return throwError('Unauthorized') } const headers = new HttpHeaders({ 'Content-Type':'application/json', 'Authorization': 'Bearer' + token }); return this.http.get<any>(this.apiUrl_User, {headers}) } Backend part in django class UserView(APIView): def get(self,request): token = request.COOKIES.get('jwt') if not token: raise AuthenticationFailed('Unauthenticated') try: payload = jwt.decode(token, 'secret',algorithms=['HS256']) except jwt.ExpiredSignatureError: raise AuthenticationFailed('Unauthenticated') user = User.objects.filter(id = payload['id']).first() serializer = UserSerializer(user) return Response(serializer.data) here is corsheaders looks like CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True ALLOWED_HOSTS = [ "http://locallhost:4200", "127.0.0.1" ] CORS_ALLOW_METHODS = ( "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ) CORS_ALLOW_HEADERS = ( "accept", "authorization", "content-type", "user-agent", "x-csrftoken", "x-requested-with", ) -
How do I link a ready-made input to a django form?
I am making a payment system website, it is necessary that the Django form is linked to a ready-made html form, {{form.as_p}} I cannot use it, what can I do here?enter image description hereenter image description hereenter image description here I couldn't find anything in the documentation about this -
Not able to show the form on my modal - Django
I am trying to get my modal to contain a form that can add a task to a to-do list. I have not made changes for the form to work yet. I just want the form to show up on my modal. This is a to-do list website I'm making, and I want to have a modal into which I can directly enter my task details through the modal in my navbar dropdown. Any help is much appreciated views.py: from django.shortcuts import render from .models import to_do from .forms import AddTaskForm def add_task(request): form = AddTaskForm() return render(request, 'navbar.html', {'form': form}) models.py from django.db import models class to_do(models.Model): title = models.CharField('Title', max_length=120) description = models.TextField(blank=True) created_on = models.DateTimeField('Created On') due_by = models.DateTimeField('Due By') status = models.BooleanField('Status', default=False) def __str__(self): return self.title forms.py from django import forms from django.forms import ModelForm from .models import to_do class AddTaskForm(ModelForm): class Meta: model = to_do fields = ("title", "description", "created_on", "due_by") urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('to-do', views.to_do_list, name='list'), ] navbar.html {% load static %} <nav class="navbar navbar-expand-lg bg-tertiary nav justify-content-center" style="background: linear-gradient(to top, #5A99FF, #3D5AFE);"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" … -
Django REST Framework Authentication access problems
I got problems with authentication. I will describe my problem in steps i made to help you understand better what the problem i got. I'm new in Django, so my code may look like trash. Firstly, i create user by using my custom user model. class CustomUserManager(BaseUserManager): def create_user(self, email, username, password=None, **extra_fields): if not email: raise ValueError('The email field must be set') email = self.normalize_email(email) user = self.model(email=email, username=username, **extra_fields) user.set_password(password) user.save(using=self._db) return user class CustomUser(AbstractUser, PermissionsMixin): email = models.EmailField(unique=True) password = models.CharField(max_length=128) username = models.CharField(max_length=30, unique=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) # Это поле определяет, активен ли пользователь (False - учетная запись деактивирована) is_active = models.BooleanField(default=True) # Это поле указывает, является ли пользователь членом персонала (в нашем случае - бустером) is_staff = models.BooleanField(default=False) objects = CustomUserManager() # Это поле определяет, какое поле будет использоваться для входа в систему вместо стандартного username USERNAME_FIELD = 'email' # Список полей, которые будут требоваться для создания пользователя с помощью команды createsuperuser REQUIRED_FIELDS = ['username'] def __str__(self): return self.email I use this url, view and serializer to create new user path('api/v1/register/', UserRegistrationView.as_view(), name='user-registration'), class UserRegistrationView(CreateAPIView): serializer_class = UserRegistrationSerializer permission_classes = [permissions.AllowAny] def create(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() … -
Problem Deploying Django Site on AWS ElasticBeanstalk
I am attempting to deploy a Django site on AWS ElasticBeanstalk for the first time. Using the CLI, when I run "eb create" I get the following error when it begins deployment via CodeCommit: Starting environment deployment via CodeCommit ERROR: TypeError - expected str, bytes or os.PathLike object, not NoneType My .git/config: [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ignorecase = true precomposeunicode = true [remote "origin"] url = https://github.com/user/repository.git fetch = +refs/heads/*:refs/remotes/origin/* [credential] UseHttpPath = true helper = !aws codecommit credential-helper $@ [remote "codecommit-origin"] url = https://git-codecommit.us-east-1.amazonaws.com/v1/repos/siterepos fetch = +refs/heads/*:refs/remotes/codecommit-origin/* pushurl = https://git-codecommit.us-east-1.amazonaws.com/v1/repos/siterepos My .elasticbeanstalk/config.yml: branch-defaults: main: environment: null group_suffix: null global: application_name: company branch: main default_ec2_keyname: company-eb default_platform: Python 3.9 running on 64bit Amazon Linux 2023 default_region: us-east-1 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: siterepos sc: git workspace_type: Application Any ideas to get this to work? -
My Class Based View(Django) code cant recognize id from SQL database
I tried to make a training project with forms. I wanted to create a code for upgrading feedbacks in the form by Class Based Views. views.py class UpdateFeedbackView(View): def get(self, request, id_feedback): feed = get_object_or_404(Feedback, id=id_feedback) form = FeedbackForm(instance=feed) return render(request, 'form_project/feedback.html', context={'form': form}) def post(self, request, id_feedback): feed = get_object_or_404(Feedback, id=id_feedback) form = FeedbackForm(request.POST, instance=feed) if form.is_valid(): form.save() return HttpResponseRedirect(f'/{id_feedback}') else: form = FeedbackForm(instance=feed) return render(request, 'form_project/feedback.html', context={'form': form}) urls.py path('<int:id_feedback>', views.UpdateFeedbackView.as_view()) html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static 'feedback/field.css'%}"> </head> <body> <h2>Оставьте отзыв</h2> <form method="post"> {% csrf_token %} {% for field in form %} <div class="form-style"> {{ field.errors }} {{ field.label_tag }} {{ field }} </div> {% endfor %} <button type="submit">Отправить</button> </form> </body> </html> When i try to type an feedback's id, i get this error TemplateDoesNotExist at /1 The code thinks that id does not exist. However i tried to write the same upgrade code by simple function and it worked well. By debugger, i realised that problem is in GET method but can't understand why. What did i wrong or miss? -
django-allauth: redirect on log-in to sign-up page if social account exists
I want to create a Google Login authentication method in my Django project. So, when a user visits my website for the first time, it will create a new user in my database and then login that user. In case a user with this email address already exists, that user will simply log in. The first part of my goal works as expected (when a user visits my website for the first time, it will create a new user in my database and then login that user), but If I'm trying to log in as an existing user, django-allauth redirects me to /accounts/social/signup/ I've tried to fix it with a CustomSocialAccountAdapter, but it didn't really help me. Could you help me please to resolve my problem? Here is my settings.py : # allauth AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] SOCIALACCOUNT_PROVIDERS = { "google": { "APP": { "client_id": os.environ.get("GOOGLE_CLIENT_ID", ""), "secret": os.environ.get("GOOGLE_CLIENT_SECRET", ""), }, "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "offline", }, }, } ACCOUNT_LOGIN_REDIRECT_URL = "home" ACCOUNT_LOGOUT_REDIRECT_URL = "home" SOCIALACCOUNT_LOGIN_ON_GET = True SOCIALACCOUNT_LOGOUT_ON_GET = True ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USER_MODEL_USERNAME_FIELD = None SOCIALACCOUNT_AUTO_SIGNUP = True ACCOUNT_LOGOUT_ON_GET = True SOCIALACCOUNT_ADAPTER = …