Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: how to use django mathfilters in CSS or style HTML tags
In this question, a user suggested this: For CSS like in your example you could use calc(). <img style="padding-top: calc({{ img.height }} / 2)" src=""/> I haven't been able to find anything similar to this using "calc", but I've tried it and it doesn't work for me. Is this the way to do it? Or is there another way to achieve this using django on CSS? I'm trying to achieve something like the following, to create a "progress bar". So I'll have a total and then other values lower than this total and do a simple calc by the rule of three. <div style="width: calc({{ value1 }} * 100 / {{ total }})"> -
How to create an object of model A out of 2 random objects of model B in Django?
I'm trying to create an app that meets two random users in Django. my question is how to create an object Meeting out of 2 random users from my User model, I want something like a for loop so that every 2 users in my database have a meeting! ps: I have only one day left to submit my work I will be so thankful if u help me this is my code so far: def createMeeting(): user_p = get_user_model() users = user_p.objects.all() all_users = users.exclude(username="Admin") n = all_users.count() for k in range(math.floor(n/2)): for user in all_users: freedate = FreeDate.objects.filter(user=user) starreds = user.userprofile.desired_user.all() matched_user = User if freedate: if starreds: for u in starreds: u_freedate = FreeDate.objects.filter(user=u.user) for dates in freedate: for matchdates in u_freedate: if dates.FreeTime == matchdates.FreeTime and dates.FreeDay == matchdates.FreeDay: matched_user = u.user else: for u in users: u_freedate = FreeDate.objects.filter(user = u) for dates in freedate: for matchdates in u_freedate: if dates.FreeTime == matchdates.FreeTime and dates.FreeDay == matchdates.FreeDay: matched_user = u if matched_user and matched_user != user and not(Meeting.objects.filter(user1=user, user2=matched_user) | Meeting.objects.filter(user1=matched_user, user2=user)): Meeting.objects.create(user1=user, user2=matched_user)` it creates only one Meeting object and i'm getting this error: TypeError: Field 'id' expected a number but got <class 'django.contrib.auth.models.User'>. … -
Importing django modules
I'm doing the django tutorial on the official website and I'm trying to figure out how to import the django modules. I have in VS code: from django.http import HttpResponse I'm getting a problem that says: Import "django.http" could not be response from source Pylance. I looked into this and it seems this is because I'm not running the virtual environment in vs code. How can I fix this? In the terminal I normally activate the venv with something like: source env/bin/activate I think I need to have that path in vs code, but I'm not entirely sure. -
Django says field does not exist when it does exist
So I created a poll model in my Django app. I'm going thorugh the polling app tutorial posted on the Django website, however, I'm using a remote MySQL database rather than a SQLite database. from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField() class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, default='') choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) I then go to terminal and type $ python manage.py makemigrations followed by $ python manage.py migrate. This all runs perfectly fine and outputs the following: Migrations for 'polls': polls/migrations/0001_initial.py - Create model Question - Create model Choice So far so good. But when I try to create a question in the shell, trouble comes $ python manage.py shell >>> from polls.models import Choice, Question >>> from django.utils import timezone >>> q = Question(question_text="What's new?", pub_date=timezone.now()) >>> q.save() Traceback (most recent call last): File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/Users/caineardayfio/Documents/CodingProjects/mysite/venv/lib/python3.7/site-packages/MySQLdb/connections.py", line 259, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'pub_date' in 'field list'") The above exception was the direct cause of … -
Can't install requirements using pip and python 3.8.5 on a Ubuntu 20.04 server
I'm trying to install python dependencies for a Django project, but I keep getting Non-user install because user site-packages disabled error. It sounds like a permission issue, I just can't figure out what went wrong. My working tools include: Django Python 3.8.5 Ubuntu 20.04 Probably worth mentioning, I am using a virtual environment for this project. Also, I have tried using root to install the packages without any luck. Any ideas on how to solve this issue is more than welcome. -
Django query using case expression to decide where inclusion
I have a query in django which I want to use in mysql and possibly with sqlite during the test stage if some conditions exist then some query would be included in the where part of the query i.e. if name is provided or year is provided the query would be select * from tab1, tab2, tab3 where tab1.name='%s' and tab1.year=%s and tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id else the query should be select * from tab1, tab2, tab3 where tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id I have made use of case expression but it was giving me error. This is the query Modelname.objects.raw("select * from tab1, tab2, tab3 where tab1.id=tab1.tb2_id and tab3.id=tab1.tb3_id and CASE '%s' WHEN None THEN '' ELSE tab1.name='%s' END and CASE %s WHEN None THEN '' ELSE tab1.year=%s END", ["user name",2]) error returned TypeError: not all arguments converted during string formatting return self.sql % self.params_type(self.params) -
How can I add a class to the autogenerated form label tag?
I have passed a queryset into a form as a field like so: class CustomCardField(forms.ModelMultipleChoiceField): def label_from_instance(self, cards): return cards class DeckForm(ModelForm): cards = CustomCardField( queryset=Card.objects.all(), widget=forms.CheckboxSelectMultiple ) class Meta: model = Deck fields = ('cards') And this autogenerates the following html: <tr> <th> <label>Cards:</label> </th> <td> <ul id="id_cards"> <li> <label for="id_cards_0"> <input type="checkbox" name="cards" value="1" id="id_cards_0"> Dog - Pas </label> </li> ... </ul> </td> </tr> Finally, my question. How can I either, add a class to the autogenerated label tag where [for="id_cards_0"], or, prevent the autogeneration of the label tag and add my own in the template? Thank you! -
Failed import for Sentry_sdk in Django
I am currently trying to get Sentry to work with my Django project. While initializing Sentry in the settings.py file I get this error: line 301, in module import sentry_sdk ModuleNotFoundError: No module named 'sentry_sdk' unable to load app 0 (mountpoint='') (callable not found or import error) I copied the docs, and I'm wondering why this is happening. Has anyone experienced this issue before? My Django version is 2.2.11 and I'm running python v 3.9.5 Here is the code for the docs if it matters (pip install --upgrade sentry-sdk) import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration sentry_sdk.init( dsn="https://examplePublicKey@o0.ingest.sentry.io/0", integrations=[DjangoIntegration()], # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production, traces_sample_rate=1.0, # If you wish to associate users to errors (assuming you are using # django.contrib.auth) you may enable sending PII data. send_default_pii=True, # By default the SDK will try to use the SENTRY_RELEASE # environment variable, or infer a git commit # SHA as release, however you may want to set # something more human-readable. # release="myapp@1.0.0", ) -
Django ignoring REQUIRED_FIELDS
I am trying to create a page with a registration and login function, however, I cannot seem to set fields as required. My models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ["first_name", "last_name"] objects = CustomUserManager() def __str__(self): return self.email forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ("first_name", "last_name", "email") And views.py def register(request): if request.method == 'POST': user_form = CustomUserCreationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.save() Profile.objects.create(user=new_user) return render(request, 'account/register_done.html', {'new_user': new_user}) else: user_form = CustomUserCreationForm() return render(request, 'account/register.html', {'user_form': user_form}) As you can see I declared first_name and last_name (I also tried to write them with a space instead of an underscore but it didn't help) as required. However, I am still perfectly able to create a user without these features. -
Whats the proper way to transmit updating data to a client via Django websockets?
Currently, I have an element that when clicked, sets up a global cooldown timer that effects all clients with the use of Django websockets. My issue is that while initially the websocket value is converted to state in my React client via componentDidMount, the websocket doesn't run again when its value changes in real time. Heres how it works in detail. The timer is updated via a django model, which I broadcast via my websocket to my React front-end with: consumer.py async def websocket_connect(self, event): print("connected", event) await self.send({ "type":"websocket.accept", }) @database_sync_to_async def get_timer_val(): val = Timer.objects.order_by('-pk')[0] return val.time await self.send({ "type": "websocket.send", "text": json.dumps({ 'timer':await get_timer_val(), }) }) This works initially, as my React client boots up and converts the value to state, with: component.jsx componentDidMount() { client.onopen = () => { console.log("WebSocket Client Connected"); }; client.onmessage = (message) => { const myObj = JSON.parse(message.data); console.log(myObj.timer); this.setState({ timestamp: myObj.timer }); }; } However, when a user clicks the rigged element and the database model changes, the web socket value doesn't until I refresh the page. I think the issue is that I'm only sending the websocket data during connection, but I don't know how to keep that "connection" open … -
Django messages not working with HttpResponseRedirect
I have the following code in Django. Only showing the relevant part messages.info(request, "Welcome ...") return HttpResponseRedirect('/') Now I dont see the messages in the '/' url How can we do this -
not able to createsuperuser in django
I am not able to createsuperuser, I am getting the following error Django Version 3.1.1 Traceback (most recent call last): File "/Users/napoleon/django-app/mysite/manage.py", line 22, in <module> main() File "/Users/napoleon/django-app/mysite/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/napoleon/django-app/pfs-venv/lib/python3.9/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) AttributeError: 'UserManager' object has no attribute 'create_superuser' basically its throwing AttributeError: 'UserManager' object has no attribute 'create_superuser' I read this also[SO-related question][1] I don't get it exactly as conveyed there. Custom User models mainapp/models.py import uuid from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class CustomUserManager(UserManager): def create_user(self, email,date_of_birth, username,password=None,): if not email: msg = 'Users must have an email address' raise ValueError(msg) if not username: msg = 'This username is not valid' raise ValueError(msg) # if not date_of_birth: # msg = 'Please Verify Your DOB' # raise ValueError(msg) # user = self.model( email=UserManager.normalize_email(email), # username=username,date_of_birth=date_of_birth ) user = self.model( email=UserManager.normalize_email(email), username=username ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password,date_of_birth): user = self.create_user(email,password=password,username=username,date_of_birth=date_of_birth) user.is_admin = True user.is_staff = … -
using ListView in django it does not diplay images after looping through image_url in my template but other database obj works
main.html {% include 'base.html' %} {% block title %} Home page {% endblock title %} {% block content %} {% for news in news %} {{ news.title }} {{ news.description | truncatewords:2 }} detail page {% endfor %} {% endblock content %} -
Access many-to-many relations of foreign object as multiple choice in model form
I have model Classroom which relates to an instance of Group of the same name. I do need the Classroom model because I am not comfortable with subsetting Group but I need further fields on Classroom which I will omit below. class Classroom(models.Model): group = models.ForeignKey(to=Group) name = models.CharField() # ... I use a model form to edit instances of Classroom. To this form I would like to add a MultipleChoiceField which allows the user of the form to add users to the classroom's group. I do understand that I could add a field members to the model form like so: class LectureClassForm(forms.ModelForm): members = forms.MultipleChoiceField() class Meta: model = LectureClass fields = ["name", "is_invitation_code_active"] But how can I populate this MultipleChoiceField with all users (User.objects.all()) and mark the ones in the group belonging to classroom (classroom.group.user_set.all()) as selected? -
Should I use Flask or Django?
I am new to web development, but I am proficient in Python. I want to build my first website, where the client can create and print their own book. The website should do a number of things: Select book content from an already existing website. Customize book features, page size, cover etc. Create pdf from the text content scraped from another site. Upload that pdf to dropbox. Connect to lulu to publish the pdf as a printed book. Take payment from the client. How should I go about this? For instance, should I use only Python (that is my best language), or will I need to learn Javascript also? If I go with Python, should I use Flask or Django? I think the former is simpler, so that sounds better. -
How to query from 2 Models in Class based views in django?
I have a model Log and another model Solutions and I am using DetailView to display details of each log Each log can have many solutions. There is a log field in the Solutions model that is Foreign Key to Log model.. Now how do I access both Log model and Solutions of that particular log in the same html template if I want to display all the solutions of that particular log below the details of the log models.py: class Log(models.Model): title = models.CharField(blank=False, max_length=500) content = models.TextField(blank=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): super().save() self.slug = self.slug or slugify(self.title + '-' + str(self.id)) super().save(*args, **kwargs) class Meta: verbose_name = ("Log") verbose_name_plural = ("Logs") def __str__(self): return f"{self.title}" def get_absolute_url(self): return reverse("log-detail", kwargs={"question": self.slug}) class Solutions(models.Model): log = models.ForeignKey( Log, on_delete=models.CASCADE, blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE,null=True, blank=True) solution = models.TextField(null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(max_length=50, null=False, blank=True) image = models.ImageField( upload_to='images', blank=True) def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.solution) super().save(*args, **kwargs) class Meta: verbose_name = ("Solution") verbose_name_plural = ("Solutions") def __str__(self): return f" … -
Django unable to save form trying to set user in a field
What I want to make, is to create a record of this class: class Order(models.Model): OPTIONS = [ ('1', 'Option 1'), ('2', 'Option 2'), ('3', 'Option 3'), ('4', 'Option 4'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.CharField(choices=OPTIONS, max_length=60) custom = models.CharField(max_length=60) date = models.DateField(default=localdate) Using this form: <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fa fa-cutlery"></i></span> </div> {{form.choice}} </div> <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fa fa-comment"></i></span> </div> {{form.custom}} </div> <div class="d-flex justify-content-center mt-3"> <input class="btn btn-success" type="submit" value="Confirm"> </div> </form> The template is rendered by this view: @login_required def createOrder(request): date = localdate() form = None item = Menu.objects.filter(date=date) if item.exists(): instance = Order.objects.filter(user=request.user,date=date) if instance.exists(): return render(request,'requestMenu.html',{'note': 'We\'re preparing your meal'}) else: user = Order(user=request.user) form = orderForm() if request.method == 'POST': form = orderForm(request.POST) if form.is_valid(): form.save(commit=False) form.user = request.user form.save() return render(request,'requestMenu.html',{'note': 'You\'re order has been saved. We\'re preparing it for you. Be patient.'}) else: return render(request,'requestMenu.html',{'note': 'Choose your meal'}) So... it supossed that Date field will come by default (already checked it, that's working good) and User will be assigned with actual logged user, after the form is completed. But then, when I go to check … -
i need to show doctors in different sections as per their experience in django project. what can i do for this?
def appointment(request): doctors = Doctor.objects.all() context = {'doctors': doctors} if request.user.is_authenticated: return render(request, 'patient/appointment.html', context) else: return redirect('home') here is the function for appointment where i need to apply filter as per doctors experience. i want to filter this doctors regarding their experience. i want this to show doctors in different sections as per their experience so i don't want to give the experience in url of website. the field name in table for experience is 'experience'. -
ModelForm customization with initial form values derived from model
I have a basic model that contains an integer. class Example(models.Model): bare_int = models.PositiveIntegerField() other_fields = models.TextField() I can create a ModelForm form where this value is inserted into a form widget for a bound form. class ExampleForm(ModelForm): class Meta: model = Example fields = ['bare_int', 'other_fields'] I want to customize the ModelForm so that the display layer applies a simple transformation: f'S{bare_int}' to the value for each model instance. The best I can do now is to apply a static default independent of model instance. class ExampleForm(ModelForm): transformed_int = CharField() class Meta: model = Example fields = ['other_fields'] def __init__(self, *args, **kwargs): super(ExampleForm, self).__init__(*args, **kwargs) self.fields['transformed_int'].initial = f'S{123}' How do I get the value of bare_int to insert in this field as the initial value? My actual model is more complex; I am trying to use the ModelForm to avoid repeating the other Example class fields rather than redefining the entire form from scratch. -
Got an error while pushing static files from Django project to bucket in google cloud storage using collect static
I am using following command to push all static files from my local Django project to bucket in Google cloud storage. DJANGO_SETTINGS_MODULE=my_project.settings.production python manage.py collectstatic settings/production.py #----------------- Cloud Storage---------------------# # Define static storage via django-storages[google] GS_BUCKET_NAME = 'project-bucket' GS_PROJECT_ID = 'xxxxxx' # STATICFILES_DIRS = [] DEFAULT_FILE_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATICFILES_STORAGE = "storages.backends.gcloud.GoogleCloudStorage" STATIC_URL = 'https://storage.googleapis.com/project-bucket/static/' # GS_DEFAULT_ACL = "publicRead" from google.oauth2 import service_account GS_CREDENTIALS = service_account.Credentials.from_service_account_file(os.path.join(BASE_DIR, 'db/key.json')) When I run './manage.py collectstatic' got following error raise exceptions.from_http_response(response) google.api_core.exceptions.Forbidden: 403 GET https://storage.googleapis.com/storage/v1/b/project-bucket/o/admin%2Fcss%2Fautocomplete.css?projection=noAcl&prettyPrint=false: project@project.iam.gserviceaccount.com does not have storage.objects.get access to the Google Cloud Storage object. Please help me in understanding this and give me respective solution. Thanks in advance! -
Django: How to pass data to redirect
def game(request): #... storage = messages.get_messages(request) for message in storage: game_msg=message break if request.method == 'POST': #some code... messages.add_message(request, messages.INFO, game_msg) return HttpResponseRedirect('game') else: form = betForm(user=request.user) print(game_msg) return render(request, 'crash/game.html', {'form': form, 'game_msg':game_msg}) my issue is when I print game_msg it shows the dictionary with all the correct info, but when I try to render it nothing shows up. if I remove the add_message and the redirect, and set game_msg like below it will display correctly. game_msg = {'isWinner':isWinner['won'], 'bet':bet, 'multiplier':multiplier, 'winnings':round(abs(winnings),2), 'crash_multiplier':round(isWinner['multiplier'],2)} if someone could explain what I'm doing wrong or a better method to send form data after a redirect without using URL parameters it would be really helpful -
How to Config Javascript ' script in Django?
I built an app using Django 3.2.3., but when I try to settup my javascript code for the HTML, it doesn't work. I have read this post Django Static Files Development and follow the instructions, but it doesn't resolve my issue. Also I couldn't find TEMPLATE_CONTEXT_PROCESSORS, according to this post no TEMPLATE_CONTEXT_PROCESSORS in django, from 1.7 Django and later, TEMPLATE_CONTEXT_PROCESSORS is the same as TEMPLATE to config django.core.context_processors.static but when I paste that code, turns in error saying django.core.context_processors.static doesn't exist. I don't have idea why my javascript' script isn't working. The configurations are the followings Settings.py BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = ( 'C:/Users/pansh/Documents/SarahPortfolio/Portfolio/Portfolio/static/', 'C:/Users/pansh/Documents/SarahPortfolio/Portfolio/formulario/static/formulario', ) urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path from django.urls.conf import include from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('formulario/', include("formulario.urls")) ] from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() Template {% load static %} <!DOCTYPE html> <html lang='es'> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href= "{% static 'formulario/style.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'formulario/scriptinfra.js' %}" type="text/javascript"></script> <title>Análisis de Infraestructura</title> </head> Directory Tree ├───formulario │ ├───migrations │ │ └───__pycache__ │ … -
Ban user from Posting a Post
I am building a small Group App and I am trying to implement a feature of banning a user by Admin for certain or particular time. When admin open - ban form then form asks for ban period of the user, which says for 10 days and 20 days. So if user selects 20 days then the ban will automatically delete after 20 days. models.py BAN_CHOICES = [ ('10_days':10_days), ('20_days':20_days), ] class Group(models.Model): user = models.ForeignKey(User, models=on_delete.CASCADE) admin = models.ManyToManyField(User,related_name='admin') time = models.BooleanField(max_length=30, choices=BAN_CHOICES) ban_users = modelsManyToManyField(User,related_name='ban_users') views.py def banning_user(request): d = timezone.now() - timedelta(days=10) ban_users = Group.objects.all() if ban_users.time == '10_days': ban.user.delete() elif ban_users.time == '20_days': ban.user.delete() BUT When i run this code then it is showing Nonetype has no attribute time. I also tried by using:- for b in ban_users: BUT it didn't work. I am new in django and I have no idea how can do it and where is the mistake. Any help would be much Appreciated. Thank you in Advance. -
Refer to variables dynamically
Context: I am creating a Django management command which will accept a positional argument. This argument is a location. My goal is to use the location value to refer to a corresponding variable. I have a global variable named Boston_webhook. This is a simple string which contains a long URL which is just a MSteams webhook... I have an additional global variable named Budapest_webhook which contains the same data type, but instead refers to a webhook related to the Budapest location. In my script, a connector variable has to be defined in order to send the message to the correct place. myTeamsMessage = pymsteams.connectorcard() If someone entered python manage.py report Boston I want to insert this into the connector params, but I am unsure how to refer to variables dynamically. Is it possible to refer to Boston_webhook when the location == 'Boston' using some sort of concatenation...? something like myTeamsMessage = pymsteams.connectorcard(location + _webhook) would be ideal I would like to avoid using conditionals as it is not scalable. I need to be able to add locations to the database without having to change code... -
Django Channels - Connection Failed (Producing error log - How to?)
I am currently setting up a basic Django Channels based chat app within my Django application. I have created all the necessary files and I have followed the instructions with regards to configuring my WebSockets for my application. Although, in the Console panel on Chrome, I am seeing the following statuses: SUCCESS {response: "Successfully got the chat.", chatroom_id: 1} (index):298 setupWebSocket: 1 (index):367 ChatSocket connecting.. (index):313 WebSocket connection to 'ws://<ip>/chat/1/' failed: setupWebSocket @ (index):313 success @ (index):385 fire @ jquery-3.6.0.js:3500 fireWith @ jquery-3.6.0.js:3630 done @ jquery-3.6.0.js:9796 (anonymous) @ jquery-3.6.0.js:10057 (index):361 ChatSocket error Event {isTrusted: true, type: "error", target: WebSocket, currentTarget: WebSocket, eventPhase: 2, …} (index):353 Chat socket closed. Where it says <ip> above, my server IP address is actually listed there, I've just removed it on here as a precaution :-) Does anyone know how if Django-Channels produces logs for error handling so I can debug the failed connection error in greater detail? I'm a little lost to where the root of the failed connection issue is occurring from within my project without some sort of log files. I do have Redis configured, and I have added my Redis Channel Layer in to my settings.py file along with listing both …