Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'django_filter'
I'm trying to use django-filter on my application but I get the error 'ModuleNotFoundError: No module named 'django_filter' Below is my code base settings.py ''' ... 'django_filter' ... ''' I have also installed django_filter in my application. -
Filter a QuerySet based on matching field in another QuerySet but restricted to an associated field in the other QuerySet
I am trying to create a filter based off two query sets of two related models (both already previously filtered). The first returns a list of IDs and concepts (names) with associated values (definitions). dqs: ID + concept + definitions + associated language (any one of four) For example: <QuerySet [<Definition: Definition (en) for #39: CBD, central business district: definition text>, <Definition: Definition (en) for #184: migration: definition text...> The second also has IDs and concepts which may or may not have matching values in the first list. tqs: ID1 + concept1 + terms (lang 1); ID1 + concept1 + terms (lang 2)...ID2 + concept1 + terms (lang 1) etc. For example: <QuerySet [<Translation: “other language term entry” (fr) for #1: abiotic component>, <Translation: “abiotic component” (en) for #1: abiotic component>, <Translation: “yet another language term entry” (es) for #1: abiotic component>...> IDs and concepts (expressed in English, the source language) are not language specific. Terms and definitions are language specific. So each concept+ID is associated with term entries and definitions in four different languages. I need to filter tqs so that it only displays entries that have matching IDs in dqs, and only in the language in which the … -
Django Form ChoiceField how to show more field name
i have a "little" problem. I want get ALL ModelChoiced field and don't know how to do that. My code parts models.py class Materials(models.Model): material = models.CharField(max_length=20,unique=True) density = models.PositiveSmallIntegerField() price = models.PositiveSmallIntegerField() def __str__(self): return self.material class Items(models.Model): article_number = models.CharField(max_length=20,blank=True,null=True) quantity = models.PositiveSmallIntegerField(blank=True,null=True) material = models.ForeignKey('Materials',on_delete=models.PROTECT,blank=True,null=True) surface =models.CharField(max_length=20,blank=True,null=True) . . . forms.py class ItemsForm(forms.ModelForm): class Meta: model = models.Items fields = "__all__" views.py def new(request): items_form = forms.ItemsForm() context = { 'items_form':items_form, } return render(request,"new.html",context) new.html {{ items_form.article_number }} {{ items_form.quantity }} {{ items_form.material }} {{ items_form.surface}} . . . So now, when open link, the generated html material code is <select name="material" id="id_material"> <option value selected>---------</option> <option value="id_1">"material_1"</option> <option value="id_2">"material_2"</option> <option value="id_3">"material_3"</option> </select> I want represent all Materials field value on each input, like this: <select name="material" id="id_material"> <option value selected>---------</option> <option value="id_1">"material_1"</option> <option value="id_2">"material_2"</option> <option value="id_3">"material_3"</option> </select> <select name="density" id="id_density"> <option value selected>---------</option> <option value="id_1">"density_1"</option> <option value="id_2">"density_2"</option> <option value="id_3">"density_3"</option> </select> <select name="price" id="id_price"> <option value selected>---------</option> <option value="id_1">"price_1"</option> <option value="id_2">"price_2"</option> <option value="id_3">"price_3"</option> </select> I tryed adding these line in ItemsForm but this method not get 'id', only just values: def __init__(self, *args, **kwargs): super(ItemsForm, self).__init__(*args, **kwargs) self.fields['density'] = forms.ModelChoiceField(queryset=models.Materials.objects.values_list('density',flat=True)) -
Displaying MySQL data on HTML page in Django - data not displaying
I am totally new to Django and I'm having a problem displaying data from a MariaDB MySQL database on a HTML page. I have a legacy database called Vision which has a table within it called SensorResult. I have added this database to the settings.py file and made a routings folder with a router_db.py file to tell the app when to use the Vision database. From this, I ran the following command: python manage.py inspectdb --database=Vision This returned a printout of each table within the database and all columns. I then used this to create a standard models.py file using this information as shown below: from django.db import models class Sensorresult(models.Model): sensorresult = models.AutoField(db_column='SensorResult', primary_key=True) # Field name made lowercase. sensorid = models.IntegerField(db_column='SensorID') # Field name made lowercase. visionid = models.IntegerField(db_column='VisionID') # Field name made lowercase. userinputid = models.IntegerField(db_column='UserInputID', blank=True, null=True) # Field name made lowercase. value = models.FloatField(db_column='Value') # Field name made lowercase. timestamp = models.DateTimeField(db_column='TimeStamp') # Field name made lowercase. class Meta: db_table = 'SensorResult' From this, I used makemigrations and migrate commands to submit this model. Now I can open the Django Shell and query the database and get a response, which makes me think that the … -
Uploading file by filefield returns Bad Request SuspiciousFileOperation
views.py if request.method == 'POST': form = MeasuringCodesForm(request.POST, request.FILES) files = request.FILES.getlist("file_field") if form.is_valid(): with transaction.atomic(): for each_file in files: new_code = MeasuringCodes(file_field=each_file) new_code.mediaplan = Mediaplan.objects.get(campaign=campaign_id) new_code.added_by = request.user new_code.save() models.py MEASURING_CODES_PARENT_PATH = 'measuring_codes/' def upload_measuring_codes_direction(instance, filename): return os.path.join(settings.MEDIA_ROOT, MEASURING_CODES_PARENT_PATH, str(instance.mediaplan.mediaplan_octi_id), filename) class MeasuringCodes(models.Model): updated = models.DateTimeField(auto_now_add=True) mediaplan = models.ForeignKey('Mediaplan', on_delete=models.CASCADE) added_by = models.ForeignKey('User', on_delete=models.PROTECT) file_field = models.FileField(upload_to=upload_measuring_codes_direction) settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL = '/files/' MEDIA_ROOT = os.path.join(BASE_DIR, 'files') And while uploading it i get bad request Detected path traversal attempt in '/x/y/files/measuring_codes/6RvVqvgp_L9cS/20220311124341089314_0' nginx.conf And on my local database everything works ok, even on wb.save(filename=os.path.join(MEDIA_ROOT, mp_file_path)) uploading works perfectly with actually same link (x/y/files/...) What should i change, something with upload_to attribute is executing badly and takes at beginning another storing route? -
How do you avoid multiple bootstrap offcanvas overriding each other?
I am coding a website using django, and want to visualize django models in my html template. I run a for loop iterating the models, and creates a offcanvas button for each. When output the model title in the different offvanvas, they overwrite each other. I have two models with titles: 628671 and 801451, but no matter which offcanvas button i click, it the same. The format {{ data.title }} is correct and i used to showcase list of models succesfully with title as in picture_1(Models with titles). So there seem to be a problem with offcanvas overriding each time i render the button in my loop. HTML code: {% for data in emotion_data %} <-- this is in the html file, it is a django-tool. <div class="offcanvas-header"> <h5 class="offcanvas-title" id="offcanvasBottomLabel">{{ data.title}}</h5> <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button> </div> <div class="offcanvas-body large"> <div id="{{ data.title }}" class="chart" style="width: 100%; min-height: 500px;"></div> </div> </div> <td><a href="#">{{ data.title }}</a></td> <td> <button type="button" id="{{ data.title }}" class="btn btn-primary" data-bs-toggle="offcanvas" data-bs-target="#offcanvasBottom" aria-controls="offcanvasBottomLabel"> Vis graf </button> </td> Picture_1:Models with title Picture_2: Offcanvas example -
Django + Javascript : Table columns build dynamically with JSON datas. Row structure broken
I retrieve on my (Django template) page 2 sets of data : 1: warehouses 2: items. With the first I wan't to create dynamically the TD's of my table after getting an Ajax search response from my view. I want to create all TD for all warehouses available in the warehouses JSON and if a product has a stock on this warehouse PK, in the same time, I populate the QTY tableBody.innerHTML += ` [...] <td>${item.fournisseur__nom}</td>`; JSON.parse(warehouses).forEach((wh) => { tableBody.innerHTML += ` <td> `; for (let i = 0; i < item.sststock.length; i++) { if (item.sststock[i].sst_id == wh.pk) { tableBody.innerHTML += item.sststock[i].qty; } }; tableBody.innerHTML += ` </td> `; }); tableBody.innerHTML += ` <td>${item.qty}</td> [...] Alas, here the result : Also new at JS, I don't understand why I need to json.PARSE twice my warehouse datas once at the top of my script, and another time in when I foreach Warehouses for building TD's. Otherwise, a warehouses.forEach is not a function error raises. JSON Warehouses : [{"model": "warehouses.warehouse", "pk": 1, "fields": {"code": "TRE"}}, {"model": "warehouses.warehouse", "pk": 2, "fields": {"code": "BAG"}}, {"model": "warehouses.warehouse", "pk": 3, "fields": {"code": "DROP"}}, {"model": "warehouses.warehouse", "pk": 4, "fields": {"code": "RN3"}}] I pass my warehouse data in … -
How to save IP address in django and check the saved value
I have to do an exercise: save IP address of admin and print an alert if this address change. I tried a lot of times, even with middleware but it doesn't work. #models.py from django.db import models from django.utils import timezone from django.conf import settings from django.contrib.auth.models import User from smapp.utils import sendTransaction from django.shortcuts import get_object_or_404 import hashlib def random_number(): return User.objects.make_random_password(length=10,allowed_chars='123456789') # Create your models here. class Lot(models.Model): author=models.ForeignKey(User,on_delete=models.CASCADE) title=models.CharField(max_length=100) text=models.TextField() created_date=models.DateTimeField(default=timezone.now) tracking_code=models.CharField(max_length=10,default=random_number) hash=models.CharField(max_length=64,default=None,blank=True) txId=models.CharField(max_length=66,default=None,blank=True) def writeOnChain(self): self.hash = hashlib.sha256(self.text.encode('utf-8')).hexdigest() self.txId = sendTransaction(self.hash) self.save() def publish(self): self.save() def __str__(self): if not self.hash: return str(self.writeOnChain()) else: return self.title class ip(models.Model): ip_address = models.GenericIPAddressField() And then my view: from django.shortcuts import render,HttpResponse from .models import Lot from .models import ip # Create your views here. def client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ipaddress = x_forwarded_for.split(',')[-1].strip() else: ipaddress = request.META.get('REMOTE_ADDR') get_ip= ip() get_ip.ip_address= ipaddress get_ip.save() return ipaddress def home_page(request): return render(request, 'smapp/home_page.html', {}) def lot_details(request): if request.method == "POST": searched = request.POST['searched'] tracks=Lot.objects.filter(tracking_code__contains=searched) return render(request, 'smapp/lot_details.html', {'searched': searched,'tracks':tracks}) else: return render(request, 'smapp/lot_details.html', {}) My question is: there is a way to do it? get_ip.save() where save my ip address and where i can check it? My problem is not to find … -
how to add print button that prints all the inserted records in django admin side?
[enter image description here][1] How Can I print all the inserted records by adding the print button? [1]: https://i.stack.imgur.com/yS1A0.png -
How to debug angular frontend with django server on vscode (Unverified Breakpoint)?
I'm running a django server for the backend of my application and angular for the frontend side. Basicaly to make my application work I start my django server: python manage.py runserver And on angular I use: ng build --output-path django_static_folder/ang --watch --output-hashing none I'm trying to debug angular code using vscode. I have an issue with "Unverified Breakpoint" on vscode. I checked many thread about this issue but none of them talked about how to debug when the server is not managed by angular using ng serve Here is my actual configuration: { "version": "0.1.0", "configurations": [ { "name": "Angular debug", "type": "firefox", "request": "launch", "url": "http://127.0.0.1:8000/", "webRoot": "${workspaceFolder}", } ] } The workspaceFolder is my angular workspace folder. The url is the one from django server. So when I start the debugger, the firefox app launch and I'm in my application but I cannot put any breakpoint. I believe that the issue is coming from the fact that I'm not using angular server. Maybe I should but then I don't know how to redirect to the correct url on the django server side ? Can anyone help me on this subject ? -
raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'generate_payroll' with no arguments not found
this is my views.py def qualified(request, employee_id): current_date = datetime.date.today() _history = PayrollModel.objects.all() for her in _history: if(her.employee_id_id == employee_id): # mnt = her if((current_date.month != her.month_year.month and current_date.month > her.month_year.month) and current_date.year == her.month_year.year): return messages.success(request, "HAPPY BD") else: return messages.success(request, "SAD BD") def generate_payroll(request, employee_id): qualification = qualified(request, employee_id=employee_id) current_date = datetime.date.today() if (qualification == True): overTimeValue = calculate_overtime(employee_id) allowanceValue = calculate_allowance(employee_id) bonusValue = calculate_bonus(employee_id) employee = EmployeeModel.objects.get(pk=employee_id) salary = PayGradeModel.objects.get(pk=employee.basic_salary_id) ssf = calculate_ssf(salary) netValue = (float(salary.amount) + float(overTimeValue) + float(bonusValue) + float(allowanceValue)) - float(ssf) # allowanceValue payroll = PayrollModel.objects.create(employee_id_id=employee_id) payroll.month_year = current_date payroll.basicSalary = salary.amount payroll.ssf_deduction = float(ssf) payroll.over_time = float(overTimeValue) payroll.bonus = float(bonusValue) payroll.allowance = allowanceValue payroll.gross_pay = salary.amount payroll.net_salary = float(netValue) payroll.save() messages.success(request, 'payroll generated successfully') return HttpResponseRedirect('/get_payroll') else: # payrolls = PayrollModel.objects.filter(employee_id_id=employee_id) return render(request, 'payrolls/get_payroll.html', {'payrolls': payroll} models.py class PayrollModel(models.Model): month_year = models.DateField(null=True) # month_year = MonthField( # "Month value", help_text="some help...", null=True) gross_pay = models.CharField(max_length=100, null=True) bonus = models.CharField(max_length=100, null=True) allowance = models.CharField(max_length=100, null=True) ssf_deduction = models.CharField(max_length=100, null=True) over_time = models.CharField(max_length=100, null=True) net_salary = models.CharField(max_length=100, null=True) employee_id = models.ForeignKey( EmployeeModel, on_delete=models.CASCADE, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True, null=True) class Meta: db_table = 'payrolls' ordering = ['-updated', '-date_created'] urls.py path('employees/<int:pk>/payrolls/generate_payroll', views.generate_payroll, name='generate_payroll'), … -
How to manually create a cron job to run a Django script?
I have been trying to run some code as a cron job using Django. There are a number of packages that help do this, but they do not seem to support the latest Django version (4.0). Instead of continuing to search for packages, I was wondering if it is possible for me to simply write a python script within my Django folder structure, and manually configure a cron job to run this. Something like setting up: */30 * * * * python3.8 /var/djangoproject/crons/cron.py Is this possible? Is there any drawback or risk in doing it like this instead of using a package that is made for this? I don't see anyone recommending this so before implementing it I wanted to see if this is a good idea. -
After Changing Python Version 3.6 to 3.10 I got cannot import name 'Callable' from 'collections'
File "C:\Users\Codertjay\PycharmProjects\Teems_App_Kid\teems_app_kid_init_.py", line 5, in from .celery import app as celery_app File "C:\Users\Codertjay\PycharmProjects\Teems_App_Kid\teems_app_kid\celery.py", line 3, in from celery import Celery File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery\five.py", line 306, in getattr module = import(self.object_origins[name], None, None, [name]) File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery\app_init.py", line 14, in from celery import state File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery_state.py", line 20, in from celery.utils.threads import LocalStack File "C:\Users\Codertjay\PycharmProjects\brownie\Teems_App_Kid\lib\site-packages\celery\utils_init.py", line 20, in from collections import Callable ImportError: cannot import name 'Callable' from 'collections' (C:\Users\Codertjay\AppData\Local\Programs\Python\Python310\lib\collections_init_.py) -
Django Rest Framework -Serializer inside serializer using same instance
So, I have a weird legacy issue where I have one model "Data", and for serialization purposes I need to restructure the fields. class Data(models.Model): id ... field_a field_b field_c date Then I have the serializers: class DataInfoSerializer(ModelSerializer): class Meta: model = Data fields = ['field_a', 'field_b', 'field_c'] class DataSerializer(ModelSerializer): data_info = DataInfoSerializer(required=False, read_only=True) class Meta: model = Data fields = ['id', 'date', 'data_info'] Now I somehow have to get DRF to use the same instance of Data that is passed into the "DataSerializer" to render the DataInfoSerializer. Any ideas how to achieve this? Or a better way. -
Data view in html table from django views
I am trying to display data the tables from the database in some tables in an HTML template from django views. The problem is that the words are in a list and I want each word to be in each field in the table, How can I do that? views.py: if request.method == 'POST': context = {} tp = request.POST.get('tp') ms = request.POST.get('mode_selection') elif tp == "Download" or tp == "Preview": usr = User.objects.get(username=request.user) if ms=='2': data = WordDifferentTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5', 'result') hds = ['word1', 'word2', 'word3', 'word4', 'word5', 'result'] elif ms=='3': data = LogicAnaloguiesTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5', 'result', 'distance_to_word12') hds = ['word1', 'word2', 'word3', 'word4', 'word5', 'result', 'distance_to_word12'] elif ms=='4': data = SimilarWInContextTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23') hds = ['word1', 'word2', 'word3', 'word4', 'word5', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'] else: data = WordsTable.objects.filter(user=usr).values_list('word1', 'word2', 'word3', 'word4', 'word5',) hds = ['word1', 'word2', 'word3', 'word4', 'word5',] return render (request, "base.html",context) else: return render (request, "base.html") HTML table: {% if data %} <div style="padding-top: 30px" class="row"> <h3 align="center">Preview</h3> <table style="border: 1px solid #dddddd;"> <thead> <tr style="border: 1px solid;"> {% for h in hds %} <th style="border: 1px solid;">{{h}}</th> {% endfor %} </tr> </thead> <tbody style="border: 1px solid;"> {% … -
How to set up a project using Saleor with a default django frontend
I want to start a project where I build a webshop and I got interested in Saleor. I would like to use this with the "default" django frontend. I was wondering how to start setting up the project. I want to fork the project but want to be able to update from origin when possible. For my project I might need to change models to my liking. What had in mind is for example the product model that I create a seperate app within saleor and make my own models that inherits from the Saleor products. But i don't know if this is the best way to do this. And does anybody else have an idea or suggestion on how to start this? Thanks -
Django framework project name is not valid [closed]
'rgshop.' is not a valid project name. Please make sure the name is a valid identifier. -
django and javascript question show and hide edit form from list of selected queries
I have the following in my index <div id="posts"> {% for post in posts %} <div class="card"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'profile' post.user.username %}">{{post.user.username}}</a> wrote:</h5> {%if post.user_id == user.id %} <div class="cardn"> <a href="#" onclick="editpost()">Edit</a> <div class="card-body" id="card-body" style="display: none"> <form action="editpost/{{post.id}} " method="post"> {% csrf_token %} <div class="form-group"> <label for="post_text" class="h4">Edit Post</label><br> <textarea name="post_text">{{post.text}}</textarea> </div> <button type="submit" class="btn btn-primary btn-sm">Edit</button> </form> </div> </div> {%endif%} <p class="card-text" id="post_text_{{post.id}}"> {{ post.text }}</p> <p class="card-text"><small class="text-muted">on: {{post.post_date}}</small></p> <p class="card-text"> <div data-id="{{post.id}}" class="card-link {% if post.current_like > 0 %} fas {%else%} far {% endif %} fa-heart">&nbsp<small class="text-muted">{{post.like_set.count}}</small> </div> </p> </div> </div> {% empty %} <h2>No posts</h2> {% endfor %} what i would like to reach is to show only the edit form for the clicked edit button using javascript here is my view def editpost(request, id): post = Post.objects.get( id=id) if request.method == "POST": text = request.POST.get("post_text") Post.objects.filter( id=id, user_id=request.session['_auth_user_id']).update(text=text) return HttpResponseRedirect(reverse("index")) else: return render(request, "network/editpost.html", { 'post': post }) my JS thats not working document.addEventListener("click", editPost); function editPost(event){ // Listener sees triggering event const clickedThing = event.target; // Event has useful properties const userCard = clickedThing.closest(".cardn"); if(userCard){ // Makes sure button has a `card` ancestor before proceeding // Now, with … -
Authorization in react with django rest api backend
I was trying to make an app where users could come and make rooms and their friend could join the room. I am using Django rest_framework as the backend and react as the frontend. For create room, the logic I was trying to implement was that if the user has already made a room and somehow clicking on create room the old room would be returned instead of creating a new room (I was trying to store the session id which then Django uses to retrieve the room if available. The request is made by axios in app.js. But each time the user press Create Room the session id is getting refreshed thus creating a new room. This is the posting part in App.js createRoom = () => { axios.post('http://localhost:8000/api/createroom', { withCredentials: true, }) .then(res => { const data = res.data; console.log(data); }) .catch(err => { console.log(err); }) } Django view to handle post request class CreateRoomView(APIView): def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset.first() else: room = Room(host=host) room.save() return Response(RoomSerializer(room).data, status=status.HTTP_201_CREATED) My logic seems to work in postman but not in react. Can someone explain what I … -
SSH Tunnel to private RDS instance from django
I have a django application and a RDS instance in a private VPC. I would to connect to it from my local machine, using a ssh tunnel. I already have this configured and I have tried the connection from pg-admin so there should be no problem in that configuration. My problem now is how to make that ssh tunnel in django. I have tried this solution, but it looks like sshtunnel python package does not support openssh keys.. I have tried to generate a valid key with ssh-keygen -t rsa but it still contains an OPENSSH private key. I think that's because I'm generating the key from MacOs. So I generated from a Linux environment and added it correctly. Now, my configuration looks like this: from sshtunnel import SSHTunnelForwarder ssh_tunnel = SSHTunnelForwarder( '<ec2 host amazon>', ssh_private_key='~/ec2-db', ssh_private_key_password='', ssh_username='ubuntu', remote_bind_address=('localhost', 5432), ) print("Here") ssh_tunnel.start() print("THere") DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'HOST': '<rds amazon dns>', 'PORT': ssh_tunnel.local_bind_port, 'NAME': '***', 'USER': '***', 'PASSWORD': '***', }, } The server with that configuration can start, but I cannot access it on localhost:8000 so I suppose the db connection has been made successfully but now I cannot check it. Any idea what may be … -
Hosting more than one django project on Apache Vhosts
Am trying to host more than one django projects [USING WINDOWS] on apache using virtual hosts same ip address but different port eg. 91 and 92 respectively. Whenever I call port 91 return project A but when I call port 92 still return project A. Virtual Hosts configurations are per image below. Static contents are served by nginx -
Django Channels consumers.py scope['user'] returns anonymousUser
I'm trying to create one to one chat but when I'm trying to get self.scope['user'] it returns AnonymousUser consumers.py class ChatConsumer(SyncConsumer): def websocket_connect(self,event): #error me = self.scope['user'] other_username = self.scope['url_route']['kwargs']['username'] other_user = User.objects.get(username=other_username) self.thread_obj = Thread.objects.get_or_create_personal_thread(me,other_user) self.room_name = f'{self.thread_obj.id}_service' print(f"{self.channel_name} connected") async_to_sync(self.channel_layer.group_add)(self.room_name,self.channel_name) self.send({ 'type':'websocket.accept' }) def websocket_receive(self,event): print(f"{self.channel_name} message received {event['text']}") msg = json.dumps({ 'text':event.get('text'), 'username':self.scope['user'].username }) async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type':'websocket.message', 'text':msg } ) def websocket_message(self,event): print(f"{self.channel_name} message sent {event['text']}") self.send({ 'type':'websocket.send', 'text':event.get('text') }) def websocket_disconnect(self,event): print(f"{self.channel_name} disconnected") async_to_sync(self.channel_layer.group_discard)(self.room_name,self.channel_name) print(event) routing.py from channels.routing import ProtocolTypeRouter,URLRouter from django.urls import path from .consumers import ChatConsumer,EchoConsumer from channels.auth import AuthMiddlewareStack import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = ProtocolTypeRouter({ "http": get_asgi_application(), 'websocket': AuthMiddlewareStack( URLRouter([ path('ws/chat/',EchoConsumer()), path('ws/chat/<str:username>/',ChatConsumer()), ]) ) }) I think the problem is here in auth.py: @database_sync_to_async def get_user(scope): """ Return the user model instance associated with the given scope. If no user is retrieved, return an instance of `AnonymousUser`. """ # postpone model import to avoid ImproperlyConfigured error before Django # setup is complete. from django.contrib.auth.models import AnonymousUser if "session" not in scope: raise ValueError( "Cannot find session in scope. You should wrap your consumer in " "SessionMiddleware." ) session = scope["session"] user = None try: user_id = _get_user_session_key(session) … -
Django Form: How to create a new related object to a multiple select widget
I am quite sure I am missing something obvious at this point. Lets say I want to create a planed trainingssession which model looks like this: class PlannedTrainingSession(models.Model): created_by = models.ForeignKey(Member, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) aimed_date = models.DateField(null=True, blank=True) team = models.ForeignKey(Squad, null=True, blank=True, on_delete=models.CASCADE) run = models.ForeignKey(PlannedRun, null=True, blank=True, on_delete=models.CASCADE) and a run which model looks like this: class PlannedRun(models.Model): name = models.CharField(max_length=200, blank=True, null=True) description = models.CharField(max_length=5000) distance = models.PositiveIntegerField(null=True, blank=True) effort = models.CharField(max_length=8, choices=[('low', _('low')), ('moderate', _('moderate')), ('intense', _('intense'))], blank=True) Now I basically want to recreate the functionality of the django admin interface, where I could create a PlannedTrainingSession with a form and select or add a related PlannedRun. So basically an add button next to the selection drop down which then opens a new form in a tab. How would I achieve that? -
How to select different ModelForms based on select value for DJANGO model form
I have a list of values. Within the list of values is a status which has a hyperlink to a particular model form. I want to dynamically change the hyperlink based on the select value to direct the user to different forms based on the select value. So, for example, when the Model value is pending, I want the hyperlink to go to the pending form. When the status is invoice sent and the use clicks the hyperlink I want the user to to go to the payment form. The code is below <table id="example1" class="table table-bordered table-striped" data-order='[[ 0, "desc" ]]' data-page-length='25'><button onClick="refreshPage()" class="btn btn-secondary float-right" title="Refresh"><i class="fa fa-sync"></i></button> <thead> <tr> <th>Script No.</th> <th>Entered on</th> <th>Script Type</th> <th>Patient</th> <th>Address</th> <th>Email</th> <th>Contact No</th> <th>Product</th> <th>Form</th> <th>Units</th> <th>Dispensing Price</th> <th>Status</th> <th>Dispatch Date</th> <th>Worksheet ID</th> <th></th> </tr> </thead> <tbody> {% for script in scripts %} <tr> <td>{{script.pk}}</td> <td>{{script.entered_on}}</td> <td>{{script.get_script_type_display}} <td>{{script.patient}}</td> <td>{{script.patient.address}}&nbsp;{{script.patient.city}}&nbsp;{{script.patient.AU_states}}&nbsp;{{script.patient.postal_code}}</td> <td>{{script.patient.email}}</td> <td>{{script.patient.mobile_number}}</td> <td>{{script.product}}</td> <td>{{script.product.form.description}}</td> <td>{{script.quantity}}</td> <td>$&nbsp;{{ script.dispensing_price }}</td> {% if script.dispatch_date is not none %} <td>{{script.get_script_status_display}}</td> {% else %} <td> <a class="edit" href="#" data-url="{% url "script:script_update_status" script.pk %}">{{script.get_script_status_display}}</a></td> {% endif %} {% if script.dispatch_date is none %} <td>Not Sent</td> {% else %} <td>{{script.dispatch_date}}</td> {% endif %} {% if script.document_id is none … -
When user registers to my app I have to collect: landing url and timestamp of landing url
Scenario: User clicks a link on some forum or ad and he lands on: myapp.com/?lg=1231231 ( or myapp.com/landing/bobby - we don't have these yet but I mean this should be global - not just on home route ) we have to store that landing page url and timestamp when he landed in session. User can then browse the site ( unregistered ) - and then he might decide to sign up - and we want that information stored. How can I accomplish this task?