Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
oath2 (fusionauth) in Django-Rest-Framework and React
I am sure there is something I fundamentally do not understand about oath2. I am trying to make django-rest-framework and react work w/ fusionauth. In react I have a button that redirects to the fusionauth authentication page. Once a user successfully logs into fusionauth, it sends a code to a redirect URL on the django backend. That DRF view exchanges the code for an authentication token and some other other info like an ID. Using that ID, I can find a corresponding (local) django user and generate a JWT token (or whatever sort of authentication system I wind up using) for that user and return it as JSON. The bit I don't understand, is how do I pass that JSON back to the frontend? -
Gunicorn binding specifically to multi-endpoint websites running on different ports
I am using Gunicorn + NGINX to deploy a multi-endpoint Django REST application. The application runs with pipenv shell foreman start which runs 5 different websites on different ports on localhost. I am trying to deploy just a single one of these websites that runs on port 8000 using Gunicorn. However, I am facing some issues while binding shown down below. I am quite sure how to exactly bind this application using the following line: gunicorn --bind 0.0.0.0:8000 myproject.wsgi Here is the WSGI file that I am using: import os from django.core.wsgi import get_wsgi_application if not "DJANGO_SETTINGS_MODULE" in os.environ: raise Exception("DJANGO_SETTINGS_MODULE not set") os.environ.setdefault("PERFORM_TIME_CONSUMING_INITIALIZATIONS", "True") application = get_wsgi_application() And this is how the websites were exported: export default { website1: "http://localhost:8007", website2: "http://localhost:8000", website3: "http://localhost:8005", website4: "http://localhost:8010", website5: "http://localhost:8009", }; -
Limited some columm in queryset django
I tried many ways but all failed when trying to get some special columns in model my code: or I use defer test_detail=testimport.objects.defer("so_hd","noi_dung") or I use only test_detail=testimport.objects.only("so_hd","noi_dung") or even use filter and defer/only test_detail=testimport.objects.filters().def("so_hd","noi_dung") When I print print(test_detail.values("ten_kh")), there are still results Because there are some columns I rarely use, so I want to save memory and improve speed if dont get there columns Please help me -
In Django, how do I construct a serializer that captures data in a join table?
I'm using Python 3.9 and Django 3.2. I have a couple of models -- a Coop model, which has many Address models, linked through a join table (CoopAddressTags) class Coop(models.Model): objects = CoopManager() name = models.CharField(max_length=250, null=False) addresses = models.ManyToManyField(Address, through='CoopAddressTags') enabled = models.BooleanField(default=True, null=False) web_site = models.TextField() description = models.TextField(null=True) approved = models.BooleanField(default=False, null=True) self.save() class CoopAddressTags(models.Model): # Retain referencing coop & address, but set "is_public" relation to NULL coop = models.ForeignKey(Coop, on_delete=models.SET_NULL, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True) is_public = models.BooleanField(default=True, null=False) I would like to create a serializer that can parse data POSTed from a front end app taht would then save these relationships, class Coop(APIView): ... def post(self, request, format=None): serializer = CoopSerializer(data=request.data) if serializer.is_valid(): serializer.save() but I'm having trouble figuring out how to incorporate the join table part of the equation. Specifically I don't know how to capture the "is_public" field from the join table in the serializer and then save everything, since the join table needs both the Coop and Address models to exist. I have this class CoopSerializer(serializers.ModelSerializer): addresses = AddressSerializer(many=True) class Meta: model = Coop fields = '__all__' def to_representation(self, instance): rep = super().to_representation(instance) rep['addresses'] = AddressSerializer(instance.addresses.all(), many=True).data return rep def create(self, … -
How to use Django and python to create a resources webpage?
I am using Django and python to create a resources webpage. So far I have created my virtual environment and set up MySql with a database. I have also created an admin with a page and can add entries to the resources page via the admin page such as: id: 1 name: stack_overflow url:http://stackoverflow.com How do I create the webpage such that it displays and lets you manage these resources (add, remove, edit)? I'm comfortable with the URL routing but I don't know how to set my models in models.py to talk to my views.py and then use a html file as a template? -
Apache showing "Index of /" directory instead of my functional django applicate
I am using windows 10 in conjunction with XAMMP (Apache) to host my website. What it looks like: https://imgur.com/a/yCtIH4M Here is the relevant segment of my htconfigs doc. LoadModule wsgi_module "C:/Users/taber/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/taber/AppData/Local/Programs/Python/Python310" WSGIPythonPath "C:\xampp\htdocs\neostorm" ################################################################################################## # NEOSTORM.US.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName neostorm.us.to Alias /static "C:/xampp/htdocs/neostorm/static" <Directory "C:/xampp/htdocs/neostorm/static"> Require all granted </Directory> WSGIScriptAlias / "C:/xampp/htdocs/neostorm/neostorm/wsgi.py" <Directory "C:/xampp/htdocs/neostorm/neostorm"> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> ################################################################################################## # MAIL.NEOSTORM.US.TO VIRTUAL HOST # ################################################################################################## <VirtualHost *:443> ServerName mail.neostorm.us.to DocumentRoot "C:/xampp/htdocs/webmail" <Directory "C:/xampp/htdocs/webmail"> Require all granted </Directory> </VirtualHost>``` [1]: https://i.stack.imgur.com/klF8N.png [2]: https://i.stack.imgur.com/DS0a5.png -
How do I generate Django seed data for a model that has a "through" field?
I'm using Python 3.9 and Django 3.2. I want to define Address objects for my Coop models, so I have set up these models ... class Coop(models.Model): = ,,, addresses = models.ManyToManyField(Address, through='CoopAddressTags') class CoopAddressTags(models.Model): coop = models.ForeignKey(Coop, on_delete=models.SET_NULL, null=True) address = models.ForeignKey(Address, on_delete=models.SET_NULL, null=True) address_is_public = models.BooleanField(default=True, null=False) My question is, how do I generate YAML seed data that creates the address, coop, and its join table data (CoopAddressTag), linking the two? address_pks = Command.get_and_print_address_yaml(file_path, city_pks) ... for row in input_file: id = row['ID'].strip().encode("utf-8", 'ignore').decode("utf-8") ... # Output the coop print("- model: directory.coop") print(" pk:",id) print(" fields:") print(" name: \"",name,"\"", sep='') print(" types:") for entry in types: print(" - ['", entry, "']", sep='') print(" addresses: [", address_pk, "]") print(" enabled:",enabled) if phone: print(" phone:",contact_phone_pk) if email: print(" email:",contact_email_pk) print(" web_site: \"",web_site,"\"", sep='') print(" approved: True", sep='') I need the Coop to exist before I can generate the join table data (CoopAddressTag), but then I'm confused about how to then enter the address data in the Coop in the YAML. -
In django models, how to add a constraint that looks across multiple rows
In the model below, I define a user, a habit the user is trying out, the start date (required) and end date (if the habit has ended). I want to add a constraint that each user can only be actively in one habit at a time. There is conceptually a few ways to determine this: For a specific user, only one habit has a NULL end date or for a specific user, the start-end range does not overlap for any of their habits, etc. I'm not sure how to approach writing this constraint, since it is looking across multiple rows instead of checking validity within one row. Any help getting started would be appreciated. from django.db import models from django.contrib.auth.models import User from django.db.models import F, Q class HabitChoices(models.TextChoices): NUTRITION = 'nutrition', 'Nutrition' EXERCISE = 'exercise', 'Exercise' SLEEP = 'sleep', 'Sleep' STRESS = 'stress', 'Stress' ALCOHOL = 'alcohol', 'Alcohol' SMOKING = 'smoking', 'Smoking' class HabitStatus(models.Model): """ This model keeps track, at a high level, of which habit the user is currently in. """ user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) habit_name = models.CharField(max_length=10, choices=HabitChoices.choices, default=HabitChoices.NUTRITION) start_date = models.DateField() end_date = models.DateField(null=True, blank=True) def is_current_habit(self): if self.end_date == None: return True else: … -
How can I reset a forloop.counter0 in django?
I have a code in django that creates a carousel for each card item. As I am looping through each image for each specific card, I realized the forloop.counter will keep continuing until the initial for loop has finished. So in my example, i is my initial loop and p is my secondary loop. i loops through cards and p loops through images within the carousel of each card. I need to reset the counter after one i so that the carousel counter starts from the beginning so that first image of every carousel is active. I'd really appreciate any help {% for i in inspections %} <div class="card - mb-3" style="width: 40 rem;"> <div id="myCarousel" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> {% for p in photos.all %} {% if p.inspection_id == i.id %} <button type="button" data-bs-target="#myCarousel" data-bs-slide-to="{{ forloop.counter0 }}" class="{% if forloop.counter0 == 0 %} active {% endif %}" aria-current="true" aria-label="Slide {{forloop.counter0}}"></button> {% endif %} {% endfor %} </div> <div class="carousel-inner"> {% for p in photos.all %} {% if p.inspection_id == i.id %} <div class="carousel-item {% if forloop.counter0 == 0 %} active {% endif %}"> <img src="{{ p.InspImages.url }}" class="img-responsive mx-auto d-block w-80" height="300" alt="..."> </div> {% endif %} {% … -
Is there a way to install memcached on windows server 2019?
I am trying to deploy my Django 4.0 project on Windows Server 2019, I am finding it difficult to install memcached -
Python migrations custom user model
I was wondering if anyone could point me in the right direction, please? I have built a custom user model as per the below code, however, when I run 'make migrations' it doesn't seem to pick up a few of the fields I have added in the custom user model. I think this is the cause of the following error message whenever I try to create a superuser. Traceback (most recent call last): File "G:\Shares\Website\Development\Intranet\HealthcareProject4\manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 59, in execute return super().execute(*args, **options) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 184, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File ".\HealthcareProject4\Users2\models.py", line 32, in create_superuser return self._create_user(email, password, True, True, **extra_fields) File ".\HealthcareProject4\Users2\models.py", line 23, in _create_user date_joined=now, **extra_fields) File "G:\Shares\Website\Development\Intranet\HealthcareProject4\env\lib\site-packages\django\db\models\base.py", line 485, in __init__ raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg) TypeError: 'is_staff' is an invalid keyword argument for this function import datetime from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ class … -
Is there a way to add additional fields on an implicit many-to-many table in Django?
Consider the following models in models.py: class Volunteer(models.Model): account = models.OneToOneField( UserAccount, on_delete=models.CASCADE, related_name= "volunteer", primary_key=True) request_offers = models.ManyToManyField('Request', related_name="volunteers", blank = True) volunteer_communities = models.ManyToManyField('Community', related_name="volunteers", blank = True) class Request(models.Model): req_type = models.ForeignKey('RequestTypes', related_name="requests", on_delete = models.CASCADE, blank = False, null = False) A volunteer can have many request_offers(type of request). In the implicit appname_volunteer_request (many-to-many) table, I want another field called date besides the default fields -- id, request_id and volunteer_id. Is there a way to add an additional field on the implicit table without creating a through table? Thanks! :) -
Django Forms to an API payload?
I am using a Django form to generate my HTML form. I wanted to use the data from my form as an API payload. if request.method == 'POST': form = GetKeyForm(request.POST) if form.is_valid(): appkey = form.cleaned_data['appkey'] secretkey = form.cleaned_data['secretkey'] shop_token = form.cleaned_data['shop_token'] shop_domain = form.cleaned_data['shop_domain'] payload = { "account_platform": { "shop_token": {shop_token}, "shop_secret": "", "shop_domain": {shop_domain}, }, "utoken": {utoken} } headers = { "Accept": "application/json", "Content-Type": "application/json" } This is the error that I am getting: Object of type set is not JSON serializable -
ModuleNotFoundError: No module named 'django_heroku' (Python help)
I'm having a lot of trouble with deploying to heroku with the python crash course material. I have tried a few things but continually feel clueless as to why it's not working? Seems the main error seems to be: ModuleNotFoundError: No module named 'django_heroku' What i've tried so far: installing pyscopg2-binary (instead of psycopg2==2.7.*) installing django-heroku installing gunicorn A few other things as well. Thanks for your help! Here is the wsgi.py file: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning_log.settings') application = get_wsgi_application() This is in my settings.py: LOGIN_URL = 'users:login' #heroku settings import django_heroku django_heroku.settings(locals()) this is my Procfile: web: gunicorn learning_log.wsgi --log-file - here is my requirements.txt file: beautifulsoup4==4.10.0 bootstrap4==0.1.0 dj-database-url==0.5.0 dj-static==0.0.6 Django==4.0.2 django-bootstrap4==22.1 django-heroku==0.3.1 django-on-heroku==1.1.2 gunicorn==20.1.0 psycopg2-binary==2.9.3 soupsieve==2.3.1 sqlparse==0.4.2 static3==0.7.0 whitenoise==6.0.0 And here is my --tail log (sorry about the length!) (ll_env) $ heroku logs --tail 2022-03-13T20:49:27.347897+00:00 app[web.1]: Traceback (most recent call last): 2022-03-13T20:49:27.347897+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker 2022-03-13T20:49:27.347898+00:00 app[web.1]: worker.init_process() 2022-03-13T20:49:27.347898+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process 2022-03-13T20:49:27.347898+00:00 app[web.1]: self.load_wsgi() 2022-03-13T20:49:27.347899+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2022-03-13T20:49:27.347900+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2022-03-13T20:49:27.347901+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi 2022-03-13T20:49:27.347901+00:00 app[web.1]: self.callable = self.load() 2022-03-13T20:49:27.347902+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line … -
django-filter list of links
I'm using django-filter's ChoiceFilter to generate a dropdown to filter results and it works great. However a dropdown is not what I have in mind for the design, instead I would like to use a list of links, but I can't find if there is such a filter. How can I have a list of links instead of a dropdown ? Current: Desired: views.py class manufacturerFilter(django_filters.FilterSet): manufacturer=django_filters.ChoiceFilter(choices=[]) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['manufacturer'].extra['choices'] = [ (wheel, wheel) for wheel in WheelItem.objects.values_list('manufacturer', flat=True).distinct() ] -
error with 'str' object has no attribute 'save' for my django project
I take an error as 'str' object has no attribute 'save'. I couldn't find where is the problem. How can I fix it? [enter image description here][1] error screenshot: [1]: https://i.stack.imgur.com/87joO.png my model code: from django.http import HttpResponse from django.shortcuts import render, HttpResponse, HttpResponseRedirect from .models import yazi from .forms import CreateForm from django.utils.text import slugify # Create your views here. def postliste_view(request): yazilar = yazi.objects.all() return render(request, "liste.html", {"yazilar": yazilar}) def postdetail_view(request, id): yaziNesne = yazi.objects.get(id=id) return render(request, "detail.html", {"yazi" : yaziNesne}) def postcreate_view(request): form = CreateForm() return render(request, "create.html", {"form" : form} ) def formdoldur_view(request): form = CreateForm(request.POST or None, request.FILES or None) if form.is_valid(): yaziNesne = form.save(commit=False) yaziNesne = slug = slugify(yaziNesne.başlık) yaziNesne.save() return render(request, "gonderildi.html", {}) def postupdate_view(request, id): if request.GET: baslik = request.GET.get("baslik") metin = request.GET.get("metin") yaziNesne = yazi.objects.get(id=id) yaziNesne.başlık = baslik yaziNesne.metin = metin yaziNesne.save() else: yaziNesne = yazi.objects.get(id=id) return render(request, "update.html", {"yazi" : yaziNesne}) def postdelete_view(request, id): yaziNesne = yazi.objects.get(id=id) yaziNesne.delete() return HttpResponseRedirect("/post") # database api --> veritabanı işlemlerini yapan fonksiyonlar # django shell --> djangonun python kabuğu -
Set is_staff to true for new users that created new accounts from CreateView
I am having problem with Django. I am using UserCreationForm and generic CreateView in order for people to sign up and create an account. The code is as follows: Custom form: class SignUpCustomUserForm(UserCreationForm): first_name = forms.CharField(max_length=200) last_name = forms.CharField(max_length=200) email = forms.EmailField(max_length=200) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password1', 'password2'] View: class SignUpView(generic.CreateView): form_class = SignUpCustomUserForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' I do not have a model since I am using CreateView which basically handles the model. I want to automatically set every new created account as staff, but I can not figure out how to do it. Basically, I am working on a form which users can use to create an account with is_staff privileges and they can use those accounts to login to /admin (the default django admin). I tried setting model.is_staff to true in the Meta class inside the form class, but it didn't work out. Any advice or ideas is welcomed. Thank you -
bootstrap - modiyfying d-flex to not increase the width of input fields
I am currently experiencing a bug/issue that involves the use of d-flex. What is happening, upon the entering of invalid credentials, the error message that is outputted is causing the width of the input fields to change. Is there a way to still use d-flex and have the widths of the input fields fixed? Please see below my code: {% extends 'healthwithfriends/base.html' %} {% load widget_tweaks %} {% block content %} <section class="vh-100"> <div class="container h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="login-card-container"> <div class="card custom-card text-white"> <div class="card-body p-5"> <div class="d-flex justify-content-center"> <h3>Health With Friends</h3> </div> <div class="d-flex justify-content-center mt-4"> <form method="POST"> {% csrf_token %} <div class="input-group mb-3"> <span class="input-group-text"><i class="fas fa-user"></i></span> {% render_field form.username type="text" class="form-control" placeholder="Username" %} </div> <div class="input-group mb-3"> <span class="input-group-text"><i class="fas fa-key"></i></span> {% render_field form.password type="password" class="form-control" placeholder="Password" %} </div> {% if form.non_field_errors %} <ul class='form-errors'> {% for error in form.non_field_errors %} <div class="alert alert-danger"> <b>{{ error|escape }}</b> </div> {% endfor %} </ul> {% endif %} <div class="d-flex justify-content-center mt-3 login-btn-container"> <button type="submit" name="button" class="btn btn-primary login-btn">Login</button> </div> </form> </div> <div class="mt-4"> </div> <div class="d-flex justify-content-center"> <p>Don't have an account? <a href="{% url 'sign up' %}" class="link-info">Register here</a></p> </div> </div> </div> </div> </div> … -
Unable to perform migration using Django and PostgreSQL
For the project that I have been working on we are using Django as the backend and PostgreSQL as out database. I have already installed all the required files for PostgreSQL and also created a database for the project. I keep on getting the following error when I try to perform migration. This is first part of the error after running python3 manage.py migrate This is last part of the error after running python3 manage.py migrate It says that it is unable to make connection with the port but I don't have any server running. I was using docker to connect the backend with frontend, but I ran docker-compose down command to take down docker. This is how I have setup the database for my project in PostgreSQL (This is the first time I am trying to perform migration in my computer for this project)Database setup in PostgreSQL -
How to reverse lookup the foreign key in Django
I have 2 models class Vendor(models.Model): vendor_name = models.CharField(max_length=50) class Food(models.Model): vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) food_title = models.CharField(max_length=50) I want to search for the vendors based on the vendor_name as well as food_title. Currently, I am able to get the vendors using this filter: keyword = "vendor name or food title" vendors = Vendor.objects.filter(vendor_name__icontains=keyword) The above filter will only work for vendor names. But, I want to get the vendors based on the food title as well. -
Django deployment on heroku throwing ModuleNotFoundError at / No module named 'pandas'
I have pandas and numpy installed in my pipenv and have checked that my requirements.txt is up to date and everything is installed. The app works fine on localhost but when it deploys my browser throws: ModuleNotFoundError at / No module named 'pandas' Request Method: GET Request URL: https://game-recs.herokuapp.com/ Django Version: 4.0.3 Exception Type: ModuleNotFoundError Exception Value: No module named 'pandas' Exception Location: /app/recommender/algorithm/code.py, line 1, in <module> Python Executable: /app/.heroku/python/bin/python Python Version: 3.10.2 Python Path: ['/app', '/app/.heroku/python/bin', '/usr/bin/python', '/app/.heroku/python/lib/python310.zip', '/app/.heroku/python/lib/python3.10', '/app/.heroku/python/lib/python3.10/lib-dynload', '/app/.heroku/python/lib/python3.10/site-packages'] All the other modules work fine... could this be a path issue? The project was deploying well until I added in a python file importing pandas. requirements.txt asgiref==3.5.0 backports.zoneinfo==0.2.1 dj-database-url==0.5.0 Django==4.0.3 gunicorn==20.1.0 numpy==1.22.3 pandas==1.4.1 psycopg2==2.9.3 psycopg2-binary==2.9.3 python-dateutil==2.8.2 pytz==2021.3 six==1.16.0 sqlparse==0.4.2 waitress==2.1.0 whitenoise==6.0.0 Heroku build logs (no error until I try to view the site) 2022-03-13T19:35:31.010043+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed 2022-03-13T19:35:31.010043+00:00 app[web.1]: File "/app/gamerecs/urls.py", line 25, in <module> 2022-03-13T19:35:31.010043+00:00 app[web.1]: from recommender.views import ( 2022-03-13T19:35:31.010043+00:00 app[web.1]: File "/app/recommender/views.py", line 12, in <module> 2022-03-13T19:35:31.010044+00:00 app[web.1]: from .algorithm.code import getRec 2022-03-13T19:35:31.010044+00:00 app[web.1]: File "/app/recommender/algorithm/code.py", line 1, in <module> 2022-03-13T19:35:31.010044+00:00 app[web.1]: import pandas as pd 2022-03-13T19:35:31.010045+00:00 app[web.1]: ModuleNotFoundError: No module named 'pandas' 2022-03-13T19:35:31.010939+00:00 app[web.1]: 10.1.49.237 - - … -
Django Channels showing current users in a room
I'm trying to show the current users that are connected to same websocket (in my case chat room) but I have a little problem. I want to create variable that stores the users and send it trough websockets to my frontend, I've achieved that, but here is the problem. Consumers.py - approach 1 class ChatRoomConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.users: list = [] @database_sync_to_async def create_msg(self, user_id=None, message=None, room=None): if user_id is not None: sender = User.objects.get(id=user_id) msg = Message.objects.create( author=sender, message=message, room_name=room) msg.save() return msg else: get_msgs = Message.objects.filter(room_name__in=[room]) serializer = MessageSerializer(get_msgs, many=True) return serializer.data async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f'chat_{self.room_name}' self.messages = await self.create_msg(room=self.room_name) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.send(text_data=json.dumps({ 'db_messages': self.messages, })) async def disconnect(self, close_code): print(close_code) await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) type = text_data_json['type'] message = text_data_json['message'] username = text_data_json['username'] user_id = text_data_json['user_id'] self.user_id = text_data_json['user_id'] if type == 'chatroom_message': self.msg = await self.create_msg(user_id, message, self.room_name) await self.channel_layer.group_send( self.room_group_name, { 'type': type, 'message': message, 'username': username, 'user_id': user_id } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, })) # nefunkcni ukazatel momentalnich … -
How to fix render() got an unexpected keyword argument 'path'
I have this code that uses folium which uses render to the map background appearance. !pip install folium import folium carparks = folium.Map(location=[50.68, -1.2667], width = 960, height = 500, zoom_start=11) # The following loops through the location items, splitting out the car part name # and the location as a pair of latitude and longitude values. # For each location, it then plots a circle marker on the map with the name as a popup string. for name, location in locations.items(): folium.CircleMarker(location=location, popup=name, radius=20, color='blue', fill_color='blue', fill_opacity=0.2).add_to(carparks) # we create the HTML file for the map, and display it below. carparks.render(path = 'data/IOWcarparlocations.html') carparks.render_iframe = True carparks but it gives this error : TypeError: render() got an unexpected keyword argument 'path' -
Problem with saving object in django-rest-framework
This is my view where I save Order object with values from frontend: @api_view(['POST']) @permission_classes([AllowAny]) def generate_bank_transfer_order(request): if request.method == "POST": body = json.loads(request.body) first_name = body.get("firstName") last_name = body.get("lastName") full_name = f"{first_name} {last_name}" today = datetime.now() transaction_id= f'00{today.strftime("%S%M%H%d%m%y")}' code_base = body.get('code') try: code = Code.objects.get(code = code_base) new_order = Order(email=body.get("email"), message=body.get("message"), city=body.get("city"), adress=body.get("adress"), postal_code=body.get("postalCode"), phone=body.get("phone"), full_name=full_name, product_names=body.get("cart"), shipment_fee=body.get("shipmentFee"), shipment_method=body.get("shipmentMethod"), transaction_id=transaction_id, total_price=body.get("price"), code=code) new_order.save() return JsonResponse({"success":new_order.transaction_id}) except ObjectDoesNotExist: new_order = Order(email=body.get("email"), message=body.get("message"), city=body.get("city"), adress=body.get("adress"), postal_code=body.get("postalCode"), phone=body.get("phone"), full_name=full_name, product_names=body.get("cart"), shipment_fee=body.get("shipmentFee"), shipment_method=body.get("shipmentMethod"), transaction_id=transaction_id, total_price=body.get("price")) new_order.save() return JsonResponse({"success":new_order.transaction_id}) This is my Order model: class Order(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, blank=True, null=True) message = models.TextField(max_length=1000, blank=True, null=True) email = models.EmailField(max_length=255, blank=True, null=True) city = models.CharField(max_length=75, default='') adress = models.CharField(max_length=100) postal_code = models.CharField(max_length=6) phone = models.CharField(primary_key=True, max_length=9, validators=[RegexValidator(r'^\d{9}$/')]) full_name = models.CharField(max_length=100) product_names = models.TextField(max_length=5000) shipment_fee = models.IntegerField(default=0) shipment_method = models.CharField(blank=True, null=True, max_length=50) code = models.ForeignKey(Code, on_delete=models.SET_NULL, null=True) transaction_id = models.CharField(max_length=150, default=0) total_price = models.DecimalField(default=0, max_digits=12, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) accepted = models.BooleanField(default=False) shipped = models.BooleanField(default=False) def __str__(self): return f"{self.email} : {self.transaction_id}" def save(self): if not self.created_at: self.created_at = timezone.now() self.updated_at = timezone.now() return super(Order, self).save() This piece of code is not perfect, but it saves the data I need. The problem is … -
receive the data passed in the body of the request API Django Python
i search a solution to get the data passed in the body of the request on django Python. I searched on the doc and tried functions like request.data/requestPost/httpRequest.body but any not works ! (sorry for my english)