Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Setting up a webhook for a telegram bot in django
I want to make a simple telegram bot on Django, I have seen some tutorials on how to make a bot using plain python but I need to make it on Django I followed this tutorial and tried to adapt it to a Django project https://www.youtube.com/watch?v=vZtm1wuA2yc this is my views.py from typing import Final from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from telegram import Update from telegram.ext import CommandHandler, MessageHandler, filters, ContextTypes, Application API_KEY: Final = 'myapikey' BOT_USERNAME: Final = 'myusername' # Comands async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("Hello! I am fellow human!, Im the bot and I want to play a game with you.") async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("I will help you somehow") async def custom_command(update: Update, context: ContextTypes.DEFAULT_TYPE): await update.message.reply_text("This is a custom command") # Responses def handle_response(text: str) -> str: text = text.lower() if 'hello' in text: return 'Howdy' if 'how are you' in text: return 'Fine' return "Im sorry I don't understand" async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE): message_type: str = update.message.chat.type text: str = update.message.text print(f'User => {update.message.chat.id} in {message_type}: "{text}"' ) if message_type == 'group': if BOT_USERNAME in text: new_text: str = text.replace(BOT_USERNAME, '').strip() # Remove username from … -
django ORM - subqueries with Max
I'm having some issues when trying to use the Django ORM with subqueries and the Max function (db: PostgreSQL 15) On the following model: class Task(models.Model): declaration = models.ForeignKey( Declaration, null=True, default=None, on_delete=models.CASCADE, related_name="tasks", ) sequence = models.PositiveIntegerField(blank=True, null=True) # # other fields I'm trying to filter tasks related to a declaration with the highest sequence. here's my attempt: sequences = Task.objects.filter(declaration=OuterRef("declaration")).exclude(sequence__isnull=True).order_by("sequence").distinct().values("sequence") max_sequences = sequences.annotate(max_seq=Max("sequence")).values("max_seq") qs = Task.objects.filter(sequence=Subquery(max_sequences)) however iterating the qs throws this error: ProgrammingError: more than one row returned by a subquery used as an expression inspecting the SQL, looks like this: SELECT "task"."id", "task"."declaration_id", "task"."sequence" FROM "task" WHERE "task"."sequence" = ( SELECT "subquery"."max_seq" FROM (SELECT DISTINCT MAX(U0."sequence") AS "max_seq", U0."sequence" FROM "task" U0 WHERE (U0."declaration_id" = ("task"."declaration_id") AND NOT (U0."sequence" IS NULL)) GROUP BY U0."sequence" ORDER BY U0."sequence" ASC) subquery) and the execution gives back the same error. Adding LIMIT 1 to the first subquery solves it on the db shell: SELECT "task"."id", "task"."declaration_id", "task"."sequence" FROM "task" WHERE "task"."sequence" = ( SELECT "subquery"."max_seq" FROM (SELECT DISTINCT MAX(U0."sequence") AS "max_seq", U0."sequence" FROM "task" U0 WHERE (U0."declaration_id" = ("task"."declaration_id") AND NOT (U0."sequence" IS NULL)) GROUP BY U0."sequence" ORDER BY U0."sequence" ASC LIMIT 1) subquery)` but I don't know how … -
Common User management for Django project ecosystem
I have been working with Django for the last few months and have built some projects in it. I was wondering whether it is possible for the distinct Django projects to share a common-use authentication and authorization project? There is a user management portal for the internal employees where the admin can add various employees to different user roles (like a manager, etc.). I will then define in the other projects what user role can access what part of the application statically. Additional parameters: There will be read-and-write operations on the user from all the projects There will be user-specific data (not user role specific user specific) Until now I have looked at the Django multi-database support which can solve my user authentication problem, but there is a catch in the authorization part where the foreign key constraints cause some problems in the models Currently, I have written a database router and am creating a user management portal for the authentication of users from a single source. -
Chained select inputs using Django CBV
I am trying to create an interface for a teacher to set homework tasks. This homework includes a student, a chapter, and questions belonging to a selected chapter. Therein lies my problem, I would like for my chapter dropdown to limit the selection from my question dropdown. Here is the current model, I added a chapter to simplify this process however ideally the chapter is not a necessary part of the homework, it only serves as a filter for the questions. class Homework(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) chapter = models.ForeignKey( Chapter, on_delete=models.SET_NULL, null=True, related_name="chapter_homework" ) question = models.ForeignKey( Question, on_delete=models.CASCADE, related_name="homework" ) agenda = models.ForeignKey( Agenda, on_delete=models.CASCADE, related_name="homeworks" ) This is the CreationView I have modified : class HomeworkCreationView(CreateView): template_name = "agenda/homework_create.html" form_class = HomeworkForm success_url = reverse_lazy("agenda:create_homework") def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['chapters'] = Chapter.objects.filterByAuthor(self.request.user) return context def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs["user"] = self.request.user return kwargs And this is a function based view which is meant to asynchronously update the question choices : def loadQuestions(request): chapter_id = request.GET.get('chapter') questions = Question.objects.filterByChapterID(chapter_id).order_by('title') return render(request, 'agenda/question_dropdown_list_options.html', {'questions':questions}) Here is the form : class HomeworkForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop("user", None) super().__init__(*args, **kwargs) teacher = user.userToTeacher() self.fields["chapter"].queryset … -
Django - ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed
I went through a few related questions but not sure how to resolve the error when trying to use the custom User model with registration form. Error: ImproperlyConfigured: AUTH_USER_MODEL refers to model 'users.User' that has not been installed register.html <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Submit</button> </form> views.py: from django.contrib.auth.forms import UserCreationForm from .models import Users from .forms import UsersForm def registerPage(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'base/register.html', context) models.py: from django.db import models from .manager import MyUserManager from django.contrib.auth.models import AbstractBaseUser from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() class User(AbstractBaseUser): email = models.EmailField(max_length=255,unique=True,) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(default=timezone.now) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin setting.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products.apps.ProductsConfig', 'pages.apps.PagesConfig', 'services.apps.ServicesConfig', 'users' ] AUTH_USER_MODEL = 'users.User' forms.py: type hfrom django import forms from django.core.exceptions import ValidationError from .models import User class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Enter Password Again', widget=forms.PasswordInput) class … -
Django custom .mo filenames not working for translations?
I have been playing with django app translation for a while now. But as my main app is becoming more complex, I've seen that some of the strings are not anymore detected by "makemessages", probaly as they originate from lists, and are only translated in the template through a {% trans my_list_item %} tag That means that each time I'm making a makemessages, those msgids are not detected, so the django.po file is updated, and my "undetected translations" are commented out. Ok, I can live with it. My next move is to create a separate po file undetected_messages.po where I stick all the translations which remain undetected. But the translations are not happening ... even if the corresponding undetected_messages.mo file seems to be created ok, and seems to contain the right info. When I put the undetected translation in the django.po file, everthing seems to happen as expected. But not when they are in a different po file with custom namefile. Any idea why? Any idea how I could solve the issue? Subsidiary question: Any idea how I could keep the translations linked to the "admin" module of each app in a separate file ... to avoid having those translations … -
AttributeError at /signup
I am trying to add a signin feature to my movie project on django and this error is showing: AttributeError at /signin 'str' object has no attribute 'POST' this is the template, signin.html {% extends 'base.html' %} {% load static %} {% block content %} <div class="container"> <h1>Sign-in</h1> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3"> <label class="form-label"></label> <input class="form-control" type="text" name="u" placeholder="Enter your username"> <div class="form-text"></div> </div> <div class="mb-3"> <label class="form-label"></label> <input class="form-control" type="text" name="p" placeholder="Enter your password"> <div class="form-text"></div> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> {% if messages %} {% for i in messages%} <ul class='messages'> <li>{{i}}</li> </ul> {% endfor %} {% endif %} </div> {% endblock %} path from django.urls import path from movie import views app_name='movie' urlpatterns = [ path('signin',views.signin,name='signin'), ] views.py from django.contrib.auth.models import User from django.contrib.auth import authenticate,login,logout from django.contrib import messages def signin(request): if(request.method=='POST'): u=request.method.POST['u'] p=request.method.POST['p'] user=authenticate(username=u,password=p) if user: login(request,user) return home(request) else: messages.error(request,'Invalid Credentials') return render(request,'signin.html') The error is showing after clicking submit... -
Deploying django to vercel not working due to routing issues
I have a django project I am trying to host on vercel. When I configure my vercel.json as such, { "builds": [ { "src": "drinksData/wsgi.py", "use": "@vercel/python" } ], "routes": [ { "src": "/(.*)", "dest": "drinksData/wsgi.py" } ] } The application works, like the templates load but then if I try to access any of the JSON response views and treat it like an API, I get a CORS issue. So trying to follow the docs I then change it to this: { "builds": [ { "src": "drinksData/wsgi.py", "use": "@vercel/python" } ], "routes": [ { "src": "/(.*)", "dest": "drinksData/wsgi.py" } ], "headers": [ { "source": "/(.*)", "headers": [ { "key": "Access-Control-Allow-Credentials", "value": "true" }, { "key": "Access-Control-Allow-Origin", "value": "*" }, { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" }, { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" } ] } ] } But then I get a deployment issue about routes and headers clashing. So then I try using rewrites: { "builds": [ { "src": "drinksData/wsgi.py", "use": "@vercel/python" } ] ,"rewrites" : [{ "source": "/(.*)", "destination": "drinksData/wsgi.py" }], "headers": [ { "source": "/(.*)", "headers": [ { "key": "Access-Control-Allow-Credentials", "value": "true" }, { "key": "Access-Control-Allow-Origin", "value": "*" }, { … -
Django: Optimization using forms .has_changed in save method
I just noticed that django forms has a method .has_changed() and I'm just wondering if it would be a good idea for optimization to use it by overriding the save method and checking if form has changed before hitting the db? By doing this we would actually skip one unnecessary call to the db. What do you guys think about it? Would look something like this: def save(self, commit=False): property = super(PropertyPriceForm, self).save(commit=False) if self.is_valid(): ... if commit and self.has_changed(): property.save() return property -
When to use DRF Serializer's methods .save(), .create() and .to_internal_value?
On DRF documentation we have that: .to_internal_value() - For write operations. .create() - For saving instances. .save() - To persists the validated data into an object instance. It seems that we can do the same stuff with any of these. So what is the best practice to use them? -
Why are my images not loading in Django? - "GET /static/app/piechart.jpg HTTP/1.1" 404 1807
I cannot seem to load in an image in a website I'm creating in Django. I get the error "GET /static/app/piechart.jpg HTTP/1.1" 404 1807 in terminal whenever I load my site. My page's css stylesheet loads in without problems but the image does not load. These are the important snippets of code from my project files. I would assume that the error lies somewhere here. settings.py STATIC_URL = '/static/' STATIC_ROOT = "/Users/NAME_RETRACTED/Projects/stockOpt/app/static" STATICFILES_DIRS = [ BASE_DIR / "static", "/app/static", ] urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from app import views urlpatterns = [ path('admin/', admin.site.urls), path("", include("app.urls")), path('', views.index, name='views') ] .html files stylesheet link <link rel="stylesheet" type="text/css" href=" {% static 'app/styles.css' %} "> image tag <img src=" {% static 'app/piechart.jpg' %} " alt=" Image didn't load"/> This is what my file structure looks like. The image is in app/static/app/piechart.jpg. Now I assume that the problem either lies in how I referenced the static files in the .html files since when I command+click (follow link) on both references, it says "The editor could not be opened because the file was not found." OR it's something to do with … -
Format data queryset result to use in form.ModelChoiceField queryset option
I have a project in Django, where i have data in a postgres database. I want to create a form with a ModelChoiceField where i can select the data obteined in a previous queryset. When I make the queryset to get data from database: list_result_queryset = BdimMaestraDatos.objects.filter(fecha_baja__isnull=True).values_list('nombre').distinct() I get this result: <QuerySet [('PEDRO',), ('JUAN',), ('ANDRES',), ('PABLO',), ('SOFIA',)]> And when I show the results into de template, they are showed but with "dirty" format like parentesis, coma, etc. Please, How i can show in the form.ModelChoiceField query option only the names PEDRO, JUAN, PABLo, etc and not ('PEDRO',), ('JUAN',), etc.? This is my form.py code from django import forms from .models import BdimMaestraDatos, lista_queryset_nombres_activos = BdimMaestraDatos.objects.filter(fecha_baja__isnull=True).values_list('nombre').distinct() print('Resultado Queryset values list: %s' %lista_queryset_nombres_activos) class MaestraDatosForm(forms.Form): Seleccionar_Nombre = forms.ModelChoiceField(label="Nombre", queryset=lista_queryset_nombres_activos) Thanks -
DRF hisotry of all changes
How to make it possible to save the history of user actions in drf? I need a table in the database that will store: user, entity (on which changes were made), state before changes, state after changes That is, I just need to track their changes associated with the database I thought it must be some kind of middleware, but I couldn't write it -
Automatic button pressing without confirmation Django + JS
tell me, please, there is a button, you select a number and click "send", the number is saved, how to do it so that you just click on the number and it is automatically saved template <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.update }} <input type="submit" value="Send"> </form> let me know if you need more code to help me. -
Django - How to create a form to add a product and a variation to the cart?
I'm developing an e-commerce app to hone my django skills and I've reach the part where its time to add product with variations to the cart. What would be the best approach for this? My models structure is as follows: from django.db import models from ckeditor.fields import RichTextField from django.urls import reverse from mptt.models import MPTTModel, TreeForeignKey # Create your models here. class Brand(models.Model): title = models.CharField(max_length=300) slug = models.SlugField(max_length=300) brand_logo = models.ImageField(upload_to='media/PRODUCTS/BRANDS/LOGOS/') def get_absolute_url(self): return reverse('catalog:brand', args=[self.slug]) def __str__(self): return self.title class Category(MPTTModel): title = models.CharField(max_length=300) slug = models.SlugField(max_length=300) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['title'] def __str__(self): return self.title def get_absolute_url(self): return reverse('catalog:category', args=[self.slug]) class Keywords(models.Model): product = models.CharField(max_length=300) def __str__(self): return self.product class MetaKeywords(models.Model): product = models.CharField(max_length=300) Keywords = models.ManyToManyField(Keywords) def __str__(self): return self.product class ProductMetas(models.Model): product = models.CharField(max_length=300) meta_title = models.CharField(max_length=300) meta_description = RichTextField(max_length=300) meta_keywords = models.ForeignKey(MetaKeywords, related_name='meta_keywords', on_delete=models.CASCADE) def __str__(self): return self.product class ProductImages(models.Model): product_image = models.ImageField(upload_to='media/PRODUCTS/FEATURED_IMAGES/') def __str__(self): return str(self.product_image) class ProductImageGallery(models.Model): product = models.CharField(max_length=300) images = models.ManyToManyField(ProductImages) def __str__(self): return self.product class ProductAttribute(models.Model): attribute = models.CharField(max_length=300) def __str__(self): return self.attribute class ProductAttributesSet(models.Model): product = models.CharField(max_length=300) attributes = models.ManyToManyField(ProductAttribute) def __str__(self): return self.product class ProductDetail(models.Model): detail = models.CharField(max_length=300) def … -
Django queryset icontains filter but "vise versa"
I have a Model: class Sources(models.Model): ... vendor = models.CharField(max_value=128, blank=True, null=True) ... And for example some data: select id, vendor from "webgui_sources"; id | vendor ----+----------------- 6 | oracle 5 | microsoft Then I have a string like "oracle;microsoft;apache" and I need to check are there models where vendor value is included to this string. So basically I need to collect all vendors which vendor value is included to "oracle;microsoft;apache". Whereas Sources.objects.filter(vendor__icontains='oracle;microsoft;apache') produces the following SQL-query: SELECT * FROM "webgui_sources" WHERE UPPER("webgui_sources".vendor) LIKE UPPER('oracle;microsoft;apache') I need to swap the fields and get something like this: SELECT * FROM "webgui_sources" WHERE UPPER('oracle;microsoft;apache') LIKE UPPER("webgui_sources".vendor) I tried to use extra and it did the job, but since using extra is not advised I tried to create custom lookup: class IContainsReverse(PatternLookup): lookup_name = "icontains_reverse" def as_sql(self, compiler, connection): lhs_sql, params = self.process_lhs(compiler, connection) params.extend([self.rhs]) return "%s ~* {}".format(lhs_sql), params Field.register_lookup(IContainsReverse) This lookup allows me to produce a query like this: Sources.objects.filter(vendor__icontains_reverse='oracle;microsoft;apache') select * from "webgui_sources" where 'oracle;microsoft;apache' ~* "webgui_sources".vendor; More or less it works but it looks clunky and works only with PostgreSQL. I hope that there is a more Django-way solution to do that, could somebody advice any more Django-way alternatives? … -
Django Serializer with multiple database
I have a Django application. I have two databases in the backend, One is PostgreSQL and one is Redshift. I am using serializer concept in DB operation. I need to process each DB in different scenarios. But when I check the insertion in Django, getting below error, '{'care_gap_fact_id': [ErrorDetail(string='This field is required.', code='required')]}' But this field is a primary key and auto increment. below are the other details, data = { #"care_gap_fact_id": 7, "start_date_id": 10, } seriali = CaregapfactSerializer(data=data) if seriali.is_valid(raise_exception=True): try : instance = seriali.save(using='postgres') except Exception as ex: print(ex) 'postgres' is one of my databases. I tried the below method as well, database_name = 'your_database_name' database_connection = connections[database_name] # Create the serializer and save the object using the specific database connection serializer = YourSerializer(data=request.data) if serializer.is_valid(): obj = serializer.save(using=database_connection) # Process further if needed else: # Handle serializer validation errors But this is also not working. Below is my model class, class CareGapFact(models.Model): care_gap_fact_id = models.IntegerField(primary_key=True) start_date_id=models.IntegerField(null=True, blank=True) Below is my serializer class, class CaregapfactSerializer(serializers.ModelSerializer): class Meta: model = CareGapFact fields = ["care_gap_fact_id","start_date_id"] If I have removed "care_gap_fact_id" from serializer fields, I am getting the error below, Got a `TypeError` when calling `CareGapFact.objects.create()`. This may be because you … -
Send Mail using django with html template
I trying to send mail with HTML template using django. Mail send properly but can't get html tempalte **This is my View.py file ** def Mail_Send(request): name = "Shyam" mydist = { 'name': name } html_template = 'mail_template.html' render_html = get_template(html_template).render(mydist) email = EmailMessage('Welcome', render_html, settings.EMAIL_HOST_USER, ['itsupport@synergyhospital.co.in'], ) email.content_subtype='html' email.send(fail_silently=False) tesddting = { 'mailsend':'mailsend' } return render(request,"index.html",tesddting) This is my Html File <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h2>Hello This is testing</h2> <p>Hi {{name}}</p> </body> </html> **the html file is in template folder** -
Django - Abstract Models cannot be instantiated
I created two models MailGroup and Recipient (shown below). I set Recipient's abstract property to true. When I try to list the MailGroup objects using the mailGroups = MailGroup.objects.all(), I'm getting the following error TypeError: Abstract models cannot be instantiated. This is my models.py file: from djongo import models class Recipient(models.Model): recipientName = models.CharField(max_length=255, null = False) recipientMailId = models.EmailField(max_length = 255, unique = True, null = False) class Meta: abstract = True class MailGroup(models.Model): mailGroupName = models.CharField(max_length = 255, unique = True, null = False) recipients = models.ArrayField( model_container = Recipient ) class Meta: abstract = False serializers.py from rest_framework import serializers from dashboardServer.models import MailGroup class MailGroupSerializer(serializers.ModelSerializer): class Meta: model = MailGroup fields = ["id", "mailGroupName", "recipients"] views.py @api_view(["GET", "POST", "PATCH", "DELETE"]) def mailGroupsView(request): if request.method == "GET": mailGroups = MailGroup.objects.all() #throws the error which I mentioned above serializer = MailGroupSerializer(mailGroups, many = True) return JsonResponse({ "status": "success", "info": "Mail groups fetched successfully", "title": "Success", "data": serializer.data }, status = 200) I'm currently using django version 4.1.9, sqlparse 0.2.4 and djongo 1.3.6 -
How to overide the CSS of Django UserCreationForm and AuthenticationForm without losing in built functionality?
I'm using the AuthenticationForm class to log users in, and the UserCreationForm to allow users to create accounts. Everything worked when I was just rendering the default form (using {{ form.as_p }} in my HTML files. However, I wanted to make the forms look nicer so I've over ridden the forms as so: class LoginForm(AuthenticationForm): username = forms.CharField(required=True, widget=TextInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "username", "placeholder": "Username"})) password = forms.CharField(widget=PasswordInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "password", "placeholder": "Password"})) class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True, widget=EmailInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "email", "placeholder": "Email"})) password1 = forms.CharField(widget=PasswordInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "password1", "placeholder": "Password"})) password2 = forms.CharField(widget=PasswordInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "password2", "placeholder": "Confirm password"})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] widgets = { 'username': TextInput(attrs={'class': "block border border-grey-light w-full p-3 rounded mb-4", "type": "text", "name": "username", "placeholder": "Username"}), 'first_name': TextInput(attrs={'class': "block border border-grey-light w-full p-3 rounded mb-4", "type": "text", "name": "first_name", "placeholder": "First Name"}), 'last_name': TextInput(attrs={'class': "block border border-grey-light w-full p-3 rounded mb-4", "type": "text", "name": "last_name", "placeholder": "Last Name"}), } However, … -
Use one docker container's URL into another container settings file
I have a docker compose file in which I am running two services: one is for django and another one is for keycloak. However, I want to access the keycloak through URL inside django settings file which I am trying to do by getting the IPAdress of the keycloak (docker inspect keycloak | grep IPAdress) container, but this does not work. Also I tried with http://localhost:8080/ (8080 is keycloak port) which also didn't work as well. Any suggestions or idea will be appreciated. -
ctrl+c in VSCode
I am working on a Django project at the moment and usually to stop the local server from running I press ctrl+c. However, a few days ago this stopped working. I think an extension or a VSCode update has caused this. Does anyone know how I can reset this keyboard shortcut in VSCode? -
Can´t Produce to topic in Kafka using docker and python
So I'm facing an odd situation where I can connect to my kafka broker but can´t produce to the topic I created. I have three images running on same network: zookeeper,kafka and my app. I have a simple producer in my app that goes like this: import json from kafka import KafkaProducer from loguru import logger producer = KafkaProducer( bootstrap_servers=["kafka:9092"], api_version=(0, 10, 21), ) def on_send_error(excp): logger.error(f"I am an errback {excp}", exc_info=excp) # handle exception def on_send_success(record_metadata): print(record_metadata.topic) print(record_metadata.partition) print(record_metadata.offset) def produce_to_kafka(): print(producer.bootstrap_connected()) data = json.dumps({"message": f"Produzindo para o Kafka mensagem 1"}) producer.send("test_producer", value=data.encode()).add_callback( on_send_success ).add_errback(on_send_error) producer.flush() When I try to run this code segment inside my app it prints True in the bootstrap_connected function but then gives me the following error when calling send(): ERROR | apps.my_app.producer:on_send_error:12 I am an errback KafkaTimeoutError: Batch for TopicPartition(topic='test_producer', partition=0) containing 1 record(s) expired: 30 seconds have passed since batch creation plus linger time My compose setup is the following: services: myapp: image: <my_app:latest> build: context: .. dockerfile: docker/Dockerfile args: DEPLOYMENT_MODE: develop stop_signal: SIGINT environment: ports: - "8000:8000" zookeeper: image: wurstmeister/zookeeper:3.4.6 ports: - "2181:2181" kafka: image: wurstmeister/kafka ports: - "9092:9092" expose: - "9093" environment: KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9093,OUTSIDE://localhost:9092 KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT KAFKA_LISTENERS: INSIDE://0.0.0.0:9093,OUTSIDE://0.0.0.0:9092 KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE KAFKA_ZOOKEEPER_CONNECT: … -
ImportError: cannot import name 'contact_view' from 'SCcontact' (app) in Django
I am new to Django. I'm trying to create a web contact form in Django that confirms by email the receipt of the enquiry to the enquirer and notifies the site owner of the enquiry details. When I do this I am getting the following error message File "C:\Users\mikec\OneDrive\Documents\Conted\Web Applications with Python JavaScript and SQL\Sophie Canniffe Costume Design\myproject\myproject\urls.py", line 19, in from SCcontact import contact_view ImportError: cannot import name 'contact_view' from 'SCcontact' (C:\Users\mikec\OneDrive\Documents\Conted\Web Applications with Python JavaScript and SQL\Sophie Canniffe Costume Design\myproject\SCcontact_init_.py) I have a views.py form in my app (SCcontacts) as follows: from django.shortcuts import render from django.core.mail import send_mail from django.http import HttpResponseRedirect from django.urls import reverse def contact_view(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') # Send email to the user user_subject = "Thank you for your enquiry" user_message = f"Dear {name},\n\nThank you for contacting us. I have received your message and will get back to you soon.\n\nBest regards,\nSophie" send_mail(user_subject, user_message, 'noreply@sophiecanniffecostumes.co.uk', [email]) # Send email to yourself admin_subject = "New Sophie Canniffe Costumes website enquiry" admin_message = f"You have received a new contact enquiry from:\n\nName: {name}\nEmail: {email}\nMessage: {message}" send_mail(admin_subject, admin_message, 'noreply@ophiecanniffecostumes.co.uk', ['sophie_canniffe@yahoo.co.uk']) return HttpResponseRedirect(reverse('contact')) return render(request, 'contact.html') and the urls.py … -
Django import ignores sys.path
A unit test module stored in /tmp is imported in my Django project. The unit test module begins like this: import tempfile import sys sys.path.insert(0, tempfile.gettempdir()) # /tmp is first in sys.path from name_like_app import foo # foo is the function to test # name_like_app.py is in /tmp # The import looks in the app instead of /tmp! The module containing foo is stored in /tmp, but happens to be named like one of the apps in my Django project. For some reason, Django looks in the app and ignores sys.path. Why does this happen?