Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gmail django sending
Today, looking at a page about django recommendations, I got the concept of a fat model and skinny views, so I had a doubt if what it was doing was good or not and if it could be applied to a model and how? def EnvioGmail(self,Nombre,gmail): context = {"Gmail":gmail,"Nombre":Nombre} template = get_template("Correo.html") content = template.render(context)#Renderisamos la plantilla con el contexto email = EmailMultiAlternatives(#Este sirve para enviar muchos correos como html "Registro exitoso", "", settings.EMAIL_HOST_USER, [gmail] ) email.attach_alternative(content,"text/html")#Es para atajar el email y darle mas datos como el contenido y comos se mostrara email.send() def post(self,request,*args,**kwargs): Formmain = Usuarios(request.POST) if Formmain.is_valid(): Usuario = Formmain.cleaned_data["nombre"] Gmail = Formmain.cleaned_data["gmail"]#Aqui extraemos el gmail del objeto Formulario self.EnvioGmail(Usuario,Gmail) Formmain.save() return HttpResponseRedirect("/Informacion/") else: Mensaje ="Porfavor revisa tus datos" return render(request,"Base.html",{"Mensaje":Mensaje,"Formulario":Usuarios}) I hope someone can help me, I'm still learning many things about django. -
How to connect to existing instance of firefox using selenium in django and how to pass these arguments
I want to login to a page manually in firefox using selenium and use django to connect to this existing firefox browser and click on a link on this already opened page. I did see that a marionette port can be useful for this process but I am not sure how to add these arguments in the driver class and also how to call it to connect to this manually opened browser to click on an element and open a new browser. This is the driver class: class FirefoxDriver(webdriver.Firefox, CustomDriverBase): def init(self, *args, **kwargs): firefox_binary = FirefoxBinary(settings.FIREFOX_BINARY_PATH) super().init(firefox_binary=firefox_binary, *args, **kwargs) class BasePage: def init(self, driver: WebDriver): self.driver = driver def get_url(self, url: str) -> NoReturn: self.delay() self.driver.get(url=url) class HomePage(BasePage): url = 'any url which can be logged into' def get(self) -> NoReturn: self.get_url(url=self.url) self.click_button(locator_cls=locators.HomePageLocators, locator_name='submit') I want to login to a webpage manually in marionette port(and keep it open all the time) and in the HomePage class , I want to click on a link which has been opened on the marionette port and continue the process. I am not able to understand where the arguments for marionette port needs to be specified and how to click on a link … -
django make a one-to-many relationship contain a True value for only one object instance, others should revert to False on this field
I have the following django model: from django.db import models from django.db.models import Q, UniqueConstraint from django.contrib.auth.models import User import random class ReferralCode(models.Model): code_str = models.CharField(max_length=64, primary_key=True, default="".join( [chr(random.randrange(48, 123)) for y in range(64)])) active = models.BooleanField(default=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: constraints = [ UniqueConstraint( fields=["user", "active"], condition=Q(active=True), name="unique_active_code_for_user", ) ] On creation of a ReferralCode with active=True I want others to revert to False, how do I do that? Thank you -
Is there a sort of way to use Unit testing with django_tables2 with filters?
I have sql requests and the results in csv format. I already have included the ExportMixin to be able to export in csv format and compare the results. I read the documentation of django_tables2 on https://django-tables2.readthedocs.io/en/latest/index.html but didn't find a clue. I tried to integrate the basic unit testing with TestCase but couldn't apply all the filters to my queryset -
Django tests errors after changing from MemcachedCache to PyMemcacheCache
I'm in the process of upgrading my project to Django 4.1.13 from 4.0. MemcachedCache has been removed from Django 4.1 so I've switched to PyMemcacheCache. I can python manage.py runserver my local server with no problems. However, when I run the tests (with --settings=test) I get errors pymemcache.exceptions.MemcacheError: All servers seem to be down right now in settings/test.py i have CACHE_BACKEND = 'locmem:///' Test were running fine on Django 4.0 -
Django form class for unknown number of fields and type
I am very new to the django framework. I am trying to make a web application that helps students learn multiplication. I have the following problem: Lets take the multiplication of 2 numbers for exampele 532 x 42 I want to create a form class that generates only the needed input fields for all intermediate steps of the multiplication. 5 3 2 x 4 2 (1) [2][1][2][8] [1][0][6][4] ---------------- [2][2][3][4][4] In this example the brackets should represent input fields. The [] brackets are normal input fields and the () brackets are carry input fields. This is what I've tried so far: class AnswerForm(forms.Form): def __init__(self, product, *args, **kwargs): super(AnswerForm, self).__init__(*args, **kwargs) self.fieldsets = {} for index, multiplier in enumerate(product.multiplier_list): rowLength = len(str(multiplier * product.multiplicand)) fieldsetFields = [] for i in range(5, 0, -1): field_name = f'field_{i}' self.fields[field_name] = forms.CharField( label=f'Answer {i}', widget=forms.TextInput(attrs={'class': 'answer-cell', 'tabindex': i, 'maxlength': 1}), required=i <= rowLength ) fieldsetFields.append(self.fields[field_name]) # Determine if row or result if index + 1 == len(product.multiplier_list): fieldsetId = f'fieldset-{product.type}result' else: fieldsetId = f'fieldset-{product.type}row' self.fieldsets[fieldsetId] = fieldsetFields I used fieldsets to group the different types of input fields. In the template i check if the field is required. If so I print the … -
deploy two django projects with apache2 and mod_wsgi under windows server 2016
I am deploying two projects on Django, one of the two is going well but when I want to access the second, I have NOT FOUND on the browser here is my wsgi.py code from the first application: `import os,sys sys.path.append('C:/Apache24/htdocs/MEKAMBO') from django.core.wsgi import get_wsgi_application #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MEKAMBO.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "MEKAMBO.settings" application = get_wsgi_application()` here is my wsgi.py code for the second application: `import os,sys sys.path.append('C:/Apache24/htdocs/log_audit') from django.core.wsgi import get_wsgi_application #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'log_audit.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "log_audit.settings" application = get_wsgi_application() ` here is the httpd.conf code: `LoadFile "C:/Users/HELPDESK/AppData/Local/Programs/Python/Python312/python312.dll" LoadModule wsgi_module "C:/Users/HELPDESK/AppData/Local/Programs/Python/Python312/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp312-win_amd64.pyd" WSGIPythonHome C:/Apache24/htdocs/MEKAMBO/env WSGIPythonPath C:/Apache24/htdocs/MEKAMBO <VirtualHost *:80> ServerName www.mekambo.com DocumentRoot "C:/Apache24/htdocs/MEKAMBO/MEKAMBO" WSGIScriptAlias /mekambo "C:/Apache24/htdocs/MEKAMBO/MEKAMBO/wsgi.py" Alias /media/ C:/Apache24/htdocs/MEKAMBO/media/ Alias /static/ C:/Apache24/htdocs/MEKAMBO/static/ <Directory C:/Apache24/htdocs/MEKAMBO/static> Require all granted </Directory> <Directory C:/Apache24/htdocs/MEKAMBO/media> Require all granted </Directory> <Directory "C:/Apache24/htdocs/MEKAMBO/MEKAMBO"> <Files wsgi.py> Require all granted </Files> </Directory> <VirtualHost *:80> ServerName www.log_audit.com DocumentRoot "C:/Apache24/htdocs/log_audit/log_audit" WSGIScriptAlias /log_audit "C:/Apache24/htdocs/log_audit/log_audit/wsgi.py" <Directory "C:/Apache24/htdocs/log_audit/log_audit"> <Files wsgi.py> Require all granted </Files> </Directory> ` -
Extract the textContent of an element using hyperscript
I have 2 elements in the DOM <script id="info-length-lower" type="application/json">6</script> <script id="info-length-upper" type="application/json">6</script> And I need to get these in some hyperscript on one of the form fields, but nothing seems to give me a value. I've tried several variations: set lowerBound to the textContent of #info-length-lower set lowerBound to #info-length-lower.textContent ... and a few others along the way that I've forgotten now. How can I get this information out using hyperscript? -
Refer to another model and count its ManytomanyField
I have two models: class Post(models.Model): content = models.TextField(blank=False) author = models.ForeignKey("User", on_delete=models.CASCADE, related_name="author") timestamp = models.DateTimeField(auto_now_add=True) def serialize(self): likes_count = self.liked_by.all().count() return { "id": self.id, "content": self.content, "author": self.author.username, "author_id": self.author.id, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), "likes": likes_count } and class Liking_System(models.Model): users_who_like = models.ManyToManyField("User", related_name="users_liked") post = models.ForeignKey("Post", on_delete=models.CASCADE, related_name="liked_by") def __str__(self): return f"Post {self.post.id} is liked by {', '.join([user.username for user in self.users_who_like.all()])}" I want in my Post model, it linked to the Liking_System and count how many users that has liked the post and return it. How can I do that? How do I modify the "likes_count = self.liked_by.all().count()". For example my post#1 is liked by two users A and B, but it returned only 1? -
Method Not Allowed: /music/add/ "POST" Error 405 for Django rest Framework
I am creating a spotify like backend and I am trying to create a track So it would take a POST request I tried bunch of different approaches through stack overflow and any resource I could get to. POST http://127.0.0.1:8000/music/add/ Content-Type: application/json Authorization: token 3e356c812614c3d4344e0d06773c27387b1e4c12 { "title": "Evil Ways", "duration": "00:03:47", "release_date": "2023-09-03", "audio_file": "/media/tracks/Music_Library.musiclibrary.zip", "artist": 2, "album": 2, "genre": 1 } I am sending the request through a .rest file and I get the response HTTP/1.1 405 Method Not Allowed Date: Thu, 08 Feb 2024 09:11:56 GMT Server: WSGIServer/0.2 CPython/3.9.0 Content-Type: application/json Vary: Accept, Cookie Allow: OPTIONS, GET X-Frame-Options: DENY Content-Length: 41 { "detail": "Method \"POST\" not allowed." } the end point is in urls.py file from django.urls import path from . import views urlpatterns = [ # other paths # all get requests work path('add/', views.add_track) ] In my views.py file I have from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from .models import Track, Artist, Genre, Album from .serializers import TrackSerializer from rest_framework.decorators import api_view, authentication_classes , permission_classes from rest_framework.authentication import SessionAuthentication, TokenAuthentication from rest_framework.permissions import IsAuthenticated # ... other views @api_view(['GET', 'POST']) @authentication_classes([SessionAuthentication, TokenAuthentication]) @permission_classes([IsAuthenticated]) def add_track(request): if … -
How to call multiple variables in send_mail() function
enter image description here How do I call multiple variables in send_mail() message parameter function like employeeid,name, email,fromplace,toplace,vehicle,duration (see image). Also, I have stored all the data in the Script tag with the names given above and not in the views.py file. -
Django django-bootstrap-v5 works locally but failed with ModuleNotFoundError: No module named 'bootstrap5' on AWS Elastic beanstalk
I have a project that use the package: django-bootstrap-v5==1.0.11 everything works OK, but when I try to deploy to AWS Elastic Beanstalk server I get the error: ModuleNotFoundError: No module named 'bootstrap5' And when I delete the 'bootstrap5' from my INSTALLED_APPS the server is up... I'm new to Amazon EC2 service so not sure what is the write approach - Are all packages allowed? If not how can I check which one allowed and how to manually use others? will appreciate any help, Thanks! -
Django render_to_string not working on fieldname.help_text
I’m creating an app for a questionnaire and making use of the model fields help_text attribute, which represents the question of each data field. For this, I wrote some custom model form: class CustomModelForm(forms.ModelForm): """A customized ModelForm for Django. This class extends the base ModelForm class from Django's forms module. It provides additional functionality to handle errors and help text for form fields. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.errors: attrs = self[field].field.widget.attrs attrs.setdefault("class", "") attrs["class"] += " is-invalid" for field in self.fields: try: self.fields[field].help_text = self._meta.model._meta.get_field( field ).help_text except Exception: pass additionally I created a template tag together with a .html: @register.inclusion_tag("../templates/snippets/radioInlineField.html") def render_radioInlineInput_field(formfield): return {"formfield": formfield} {% with field=formfield %} <div class="col-sm-6 text-start"> {% if field.help_text %} <p class="mb-0">{{ field.help_text }}: </p> {% endif %} </div> <div class="col-sm-6 mt-0 "> {% for radio in field %} <div class="form-check form-check-inline"> {{ radio.tag }} <label class="form-check-label" for="id_{{ radio.id_for_label }}">{{ radio.choice_label }}</label> </div> {% endfor %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} </div> {% endwith %} Now everything works good with it, but if I have Form A (only consisting of the above mentioned type of fields) and … -
How to validate data when insert using raw SQL query
class Queue(models.Model): name = models.CharField(max_length=255, unique=True) api_token = models.CharField(max_length=255, default=secrets.token_hex(16)) class Message(models.Model): queue = models.ForeignKey(Queue, on_delete=models.CASCADE) subject = models.CharField(max_length=255) message = models.TextField() api_token = models.CharField(max_length=255) These are my models and I want to insert Message data using raw SQL query. But I want to match the api_token from the Message table to the selected Queue api_token when Insert. How to do that? -
Django ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS settings not fully understood
My Django server is running on 127.0.0.1:8001. I use nginx to reverse proxy my django server to port 80. The nginx config looks like this: server { listen 80; location / { proxy_pass http://127.0.0.1:8001; } location /static { root STATIC_ROOT; } } I got confused when I try to understand ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS settings. These 2 settings all don't work: ALLOWED_HOSTS = ["example.com"] CSRF_TRUSTED_ORIGINS = ["https://example.com"] Or ALLOWED_HOSTS = ["127.0.0.1"] CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1"] Only this works ALLOWED_HOSTS = ["127.0.0.1"] CSRF_TRUSTED_ORIGINS = ["https://example.com"] Can anybody explains why I need to set them differently? If possible, how does nginx reverse proxy work generally? -
(React-Django) Getting 403 Forbidden for uploading file to google cloud storage using signed url
I created signed url to upload files (mp3 video file upto 1GB) from the client side directly on cloud storage. But when I try to upload the file, I am getting following error: ` SignatureDoesNotMatch Access denied. The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method. ` This is how the URL was generated: https://storage.googleapis.com/bucket-name/filename ?X-Goog-Algorithm=GOOG4-RSA-SHA256 &X-Goog-Credential=something.iam.gserviceaccount.com%2xyz%2Fauto%2Fstorage%2Fgoog4_request &X-Goog-Date=20240207T120631Z &X-Goog-Expires=900 &X-Goog-SignedHeaders=content-type%3Bhost &X-Goog-Signature=21... Front end is in react and I am first making a call to get the signedurl and then uploading the file. React code : const responseForSignedUrl = await axios.get( `${baseUrl}/api/posts/getuploadurl/` ); if (responseForSignedUrl.status !== 200) { throw new Error("Failed to obtain signed URL."); } const signedUrl = responseForSignedUrl.data.url; // Upload video file to Cloud Storage using the signed URL const videoFormData = new FormData(); videoFormData.append("file", video_file); const uploadResponse = await axios.put(signedUrl, videoFormData, { headers: { "Content-Type": "video/mp4", }, onUploadProgress: (progressEvent) => { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); setProgress(percentCompleted); }, }); if (!uploadResponse.ok) { throw new Error("Failed to upload video file."); } Backend code for signed url generation: def generate_upload_signed_url_v4(request): """Generates a v4 signed URL for uploading a blob using HTTP PUT. Note that … -
How do I combine identical cells in a column using python xlwt?
I use python xlwt to generate an excel file (report). I can't combine the cells of the column with the same values (column A and column with totals) in any way. For example, I have attached screenshots of how I get the output now and what kind of output it needs to be brought to. My function generates a report of the following type: enter image description here Please help me to make it look like this: enter image description here Report generation function: def export_excel(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = ("attachment; filename=Numbers_" + str(datetime.datetime.now().strftime("%d/%m/%y")) + '.xls') wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Numbers', cell_overwrite_ok=True) row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Подразделение', 'Номер', 'Сумма', 'Итог (Сумма+ндс+абон.плата)', 'Итог по подразделению'] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) font_style = xlwt.XFStyle() rows = ReportFilter(request.GET, queryset=Parser.objects.all().values_list( 'attachment__attachment', 'number', 'pay', 'result')).qs rows1 = Numbers.objects.filter(is_enabled=True).values_list('attachment__attachment', 'number') res = 0 temp = [] for item1 in rows: temp.append(item1) res += item1[3] for item2 in rows1: if Parser.objects.filter(number=item2[1]): None else: item2 = list(item2) item2.append(250) item2.append(250) res += item2[3] item2 = tuple(item2) temp.append(item2) temp.sort() temp = tuple(temp) for row in temp: row_num += 1 for col_num in range(len(row)): if isinstance(row[col_num], datetime.datetime): date_time = … -
Assistance Needed with Python/Django Backend Development for Portfolio Website [closed]
I'm new to backend development and currently working on my portfolio website using Python, Django, MongoDB, and APIs. However, I'm facing some issues and could use some assistance. If anyone experienced with these technologies could lend a hand, I'd greatly appreciate it. Thanks! -
is it safe to create django-allauth confirmation email table manually?
I am building a web app using Django, and I am using Django-Allauth for the authentication. Somehow when I was inspecting the database in mysql workbench I though a saw a duplicate table named account_EmailConfirmation and before I think about it I dropped the table and both of them dropped. Idk exactly know why they appeared as 2 tables and when I dropped one the other was deleted but anyway, i decided then to create the table again manually. operations = [ migrations.CreateModel( name='EmailConfirmation', fields=[ ('id', models.AutoField(primary_key=True, auto_created=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('sent', models.DateTimeField(null=True, blank=True)), ('key', models.CharField(max_length=64, unique=True)), ('email_address_id', models.ForeignKey(to='account.EmailAddress', on_delete=models.CASCADE)), ], options={ 'db_table': 'account_emailconfirmation', }, ), ] My question is this: Is this safe and okay to do, or is it going to cause issues later on? -
CKEditor update notification
Want to remove "This CKEditor 4.22.1 version is not secure. Consider upgrading to the latest one, 4.24.0-lts." from appearing in my Django admin's RichTextUploadingField. Currently using Django CKEditor 6.7.0m all settings are in settings.py only. Configs: CKEDITOR_CONFIGS = { "default": { "skin": "moono", "toolbar": "Custom", "allowedContent": True, "extraAllowedContent": "object\[id,name,width,height\];", "extraPlugins": "iframe", "iframe_attributes": { "sandbox": "allow-scripts allow-same-origin allow-popups allow-presentation allow-forms", "allowfullscreen": "", "loading": "lazy", "referrerpolicy": "no-referrer-when-downgrade", }, "toolbar_Custom": \[ { "name": "document", "items": \[ "Source", "-", "Save", "NewPage", "Preview", "Print", "-", "Templates", \], }, { "name": "clipboard", "items": \[ "Cut", "Copy", "Paste", "PasteText", "PasteFromWord", "-", "Undo", "Redo", \], }, {"name": "editing", "items": \["Find", "Replace", "-", "SelectAll"\]}, { "name": "forms", "items": \[ "Form", "Checkbox", "Radio", "TextField", "Textarea", "Select", "Button", "ImageButton", "HiddenField", \], }, "/", { "name": "basicstyles", "items": \[ "Bold", "Italic", "Underline", "Strike", "Subscript", "Superscript", "-", "RemoveFormat", \], }, { "name": "paragraph", "items": \[ "NumberedList", "BulletedList", "-", "Outdent", "Indent", "-", "Blockquote", "CreateDiv", "-", "JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock", "-", "BidiLtr", "BidiRtl", "Language", \], }, {"name": "links", "items": \["Link", "Unlink", "Anchor"\]}, { "name": "insert", "items": \[ "Image", "Flash", "Table", "HorizontalRule", "Smiley", "SpecialChar", "PageBreak", "Iframe", "Embed", \], }, "/", { "name": "styles", "items": \["Styles", "Format", "Font", "FontSize"\], }, {"name": "colors", "items": \["TextColor", "BGColor"\]}, {"name": "tools", … -
Update with save() method doesn't work in django
I'm using multiple connections to different databases. But nothing happen when I'm trying to update data in db using save() method. I mean everything's works but data still not updated. How can I fix it? def save_object_using_dynamic_db(model, obj_id, db_alias, **kwargs): """ Save an object into the specified database alias. """ connection = connections[db_alias] print(f"{connection = }") try: obj_to_save = model.objects.using(connection.alias).get(id=obj_id) except model.DoesNotExist: # If the object doesn't exist, you may want to handle this case accordingly print(f"Object with id {obj_id} does not exist in the database.") return None for field, value in kwargs.items(): if hasattr(obj_to_save, field): print(f"{obj_to_save = }, {obj_id = }, {field = }: {value = }") setattr(obj_to_save, field, value) try: # obj_to_save.full_clean() # Check model validation obj_to_save.save(using=connection.alias) print(f"Object saved: {obj_to_save}") return obj_to_save except ValidationError as e: print(f"Validation error: {e}") return None except Exception as e: print(f"Unexpected error: {e}") return None # obj_to_save.save(using=db_alias) # print(f"{obj_to_save = }") # return obj_to_save -
IntegrityError CHECK constraint failed on Django
this is my error: IntegrityError at /caja_chica/comprobantes/9/editar/ CHECK constraint failed: caja_chica_cajachica Request Method: POST Request URL: http://127.0.0.1:8000/caja_chica/comprobantes/9/editar/ Django Version: 3.2.5 Exception Type: IntegrityError Exception Value: CHECK constraint failed: caja_chica_cajachica the problem is on my model, when i tried to save a Comprobante object trying before making an operation. This is my model Comprobante: class Comprobante(models.Model): TIPO_A = 1 TIPO_B = 2 TIPO_C = 3 TIPO_T = 4 TIPO_X = 5 TIPO_CHOICES = ( (TIPO_A, 'A'), (TIPO_B, 'B'), (TIPO_C, 'C'), (TIPO_T, 'T'), (TIPO_X, 'X'), ) caja_chica = models.ForeignKey(CajaChica, on_delete=models.PROTECT) lote = models.ForeignKey(Lote, on_delete=models.DO_NOTHING, null=True, blank=True, related_name='lote_comprobantes') numero = models.CharField(max_length=13) tipo = models.PositiveSmallIntegerField(choices=TIPO_CHOICES, default=TIPO_T) ente = models.ForeignKey(Ente, on_delete=models.PROTECT) fecha = models.DateField() partida_presupuestaria = models.ForeignKey(PartidaPresupuestaria, on_delete=models.PROTECT) detalle = models.CharField(max_length=100) importe = models.DecimalField(max_digits=7, decimal_places=2) history = HistoricalRecords() def __str__(self): return self.numero def save(self, *args, **kwargs): super(Comprobante, self).save(*args, **kwargs) self.caja_chica.disponible -= self.importe self.caja_chica.save() def get_absolute_url(self): """ Devuelve la url para acceder a una instancia particular de Comprobante. """ return reverse('caja_chica:comprobante_update', args=[str(self.id)]) this is the function that broke my model: def save(self, *args, **kwargs): super(Comprobante, self).save(*args, **kwargs) self.caja_chica.disponible -= self.importe self.caja_chica.save() and this is my model CajaChica: class CajaChica(models.Model): FUENTE_11 = 11 FUENTE_12 = 12 FUENTE_13 = 13 FUENTE_CHOICES = ( (FUENTE_11, FUENTE_11), (FUENTE_12, FUENTE_12), (FUENTE_13, … -
Django and nginx connected via a bridge network.How to parse domain and pass it to the proxy_pass?
I am working on a multi tenant app. I have nginx as a rev-proxy When a tenant registers I create a docker image and name it based on his subdomain Lets call tenant1 t1 and tenant2 t2. So t1.localhost.web to should be routed to t1.web:8000 where t1 is extracted from url in nginx by regex and concatenated to ".web:8000" and it becomes t1.web:8000 and set to proxy_pass in nginx.conf These dockers containers also have a bridged network and they can be reached by their names. So if you bash into one of these containers you can ping or curl each other by their names it worksm so they are reachable by name curl http://t1.web:8000 actually works given if you are "bash"ed into nginx container this is my config file events { worker_connections 4096; ## Default: 1024 } http { # Redirect HTTP to HTTPS server { server_name ~^(?<subdomain>.+)\.app\.dev; listen 80; location / { set $domainweb "http://$subdomain.web:8000"; proxy_pass $domainweb; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } } to debug I tried to exclude the subdomain variable and tried location / { set $domainweb "http://t1.web:8000"; proxy_pass $domainweb; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } that also did not work but when … -
Troubles AJAX Integration with Django
When I save products from ajax to db, it always redirects me to failed page and saying 500 server error views.py from cart.cart import Cart from django.http import JsonResponse from django.shortcuts import render from .models import Order, OrderItem, ShippingAddress # Create your views here. def checkout(request): if request.user.is_authenticated: try: shipping_address = ShippingAddress.objects.get(user=request.user.id) context = {'shipping': shipping_address} return render(request, 'payment/checkout.html', context=context) except: return render(request, 'payment/checkout.html') else: return render(request, 'payment/checkout.html') def complete_order(request): if request.POST.get('action') == 'post': name = request.POST.get('name') email = request.POST.get('email') address1 = request.POST.get('address1') address2 = request.POST.get('address2') city = request.POST.get('city') state = request.POST.get('state') zipcode = request.POST.get('zipcode') print(name) shipping_address = (address1 + "\n" + address2 + "\n" + city + "\n" + state + "\n" + zipcode ) cart = Cart(request) total_cost = cart.get_total() if request.user.is_authenticated: order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address, amount_paid=total_cost, user=request.user) order_id = order.pk for item in cart: OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'], price=item['price'], user=request.user) else: order = Order.objects.create(full_name=name, email=email, shipping_address=shipping_address, amount_paid=total_cost) order_id = order.pk for item in cart: OrderItem.objects.create(order_id=order_id, product=item['product'], quantity=item['qty'], price=item['price']) order_success = True response = JsonResponse({'success':order_success}) return response urls.py from django.urls import path from . import views urlpatterns = [ path('checkout', views.checkout, name='checkout'), path('complete-order', views.complete_order, name='complete-order'), path('payment-success', views.payment_success, name='payment-success'), path('payment-failed', views.payment_failed, name='payment-failed'), ] checkout.html {% include "store/base.html" %} {% … -
"Waiting list" or delay when sending emails with Django and the win32 library
I have just discovered something in the provided code, and I would like to explain it to you. During my tests with the email sending using this code, everything seemed to work correctly, but a specific issue arose. Let's say I have three emails to send: email 1, email 2, and email 3. When I send email 1, the console returns a 200 OK status, but the email doesn't reach my inbox. Then, when I proceed to send email 2, the console again returns a 200 OK status, and although a new email appears in my inbox, it turns out to be email 1. After waiting several minutes without receiving any updates or new emails, I proceed to send email 3. At this point, the console once again shows a 200 OK status, and, surprisingly, I receive a new email in my inbox, but now it is email 2. ` class ApiSendMailCreateNewReporter(APIView): def get(self, request, id_headerRequest): try: # Obtener el objeto HeaderRequest o devolver un error 404 si no existe header_request = get_object_or_404(HeaderRequest, id=id_headerRequest) # Serializar el objeto HeaderRequest serializer_header_request = HeaderRequestSerializer(header_request) usuario_id = serializer_header_request.data['id_user_id'] require_date = serializer_header_request.data['require_date'] customer = serializer_header_request.data['customer'] # Obtener la instancia de Engineers con role='admin' o …