Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Single table's column can point to multiple table in django
Let's say I have tables FormulaA, FormulaB...FormulaX, and productContent. Formula { characteristicsA, characteristicsB, ... } Now, each product will be based on only a single formula(A to X). I want to design my database in such a way, that table productContent will have two columns, productContent { product_id, -> foreign key to product table formula_id -> can point to either of table formulaA,..formulaX } Now, My concerns/requirements are: if I have product_id, how can I get it's formula detail? Can I use select_related query here? we can take help of polymorphism, like make a common table, Formula, and from there formulaA,..formulaX can inherit. and in ProductContent table, we can have a new column, formula which will point to base table. But here also, how can I achieve requirement 1? -
django-channels: page not found
I am trying to set up django-channels. I did everything according to the instructions, but when I try to connect, I get a 404 error - page not found. I make a request from the localhost to the dev server. config/base.py INSTALLED_APPS = [ "grappelli", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "adminsortable2", "channels", "corsheaders", "django_filters", "django_multilanguage_content", "django_otp", "django_otp.plugins.otp_totp", "drf_yasg", "notifications", "rest_framework", "rest_registration", "storages", "vv.announcements.apps.AnnouncementsConfig", "vv.core.apps.CoreConfig", "vv.discussions.apps.DiscussionsConfig", "vv.manage_categories.apps.ManageCategoriesConfig", "vv.messaging.apps.MessagingConfig", "vv.users.apps.UsersConfig", "vv.vital_notif.apps.VitalNotifConfig", ] ASGI_APPLICATION = "config.asgi.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(env("REDIS_HOST"), 6379)], }, }, } config/asgi.py import os import sys import django from django.core.asgi import get_asgi_application app_path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir)) sys.path.append(os.path.join(app_path, "vv")) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.base") django.setup() django_asgi_app = get_asgi_application() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from config.routing import websocket_urlpatterns application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": URLRouter(websocket_urlpatterns), }) routing.py from django.urls import path from vv.messaging.consumers import MarkAsReadConsumer websocket_urlpatterns = ( path("ws/mark/", MarkAsReadConsumer.as_asgi()), ) runner.sh #!/bin/sh daphne -b 0.0.0.0 -p 8000 config.asgi:application -v2 python manage.py runworker -v2 client.js let socket = new WebSocket("ws://<ip>/ws/mark/"); docker-compose.yml version: "3.7" x-env_file: &env_file env_file: - ./.env services: nginx: build: ./nginx container_name: vv-fix-nginx ports: - "5555:80" depends_on: - backend networks: - vv-fix-network redis-vv: image: redis:alpine container_name: vv-fix-redis volumes: - vv_fix_redis_volume:/var/lib/redis/data/ ports: - … -
django sign up form not storing the username
I have a sign up form that does not store the username properly, other fields are stored successfully. Shouldn't it save the username because it is in the fields ? I saw that I cannot login and this is because the row in the table does not have the username. views.py class SignUpFormView(FormView): form_class = SignUpForm template_name = 'users/authentication/login/signup.html' def post(self, request): form = self.form_class(data=request.POST) if form.is_valid(): user = form.save(commit=False) # some logic here user.save() messages.success( request, "Great! You are able to login now.") return redirect('login') else: messages.error(request, form.errors) return redirect('login') forms.py class CustomUserCreationForm(UserCreationForm): def clean_username(self): username = self.cleaned_data["username"] try: TbUser.objects.get(username=username) except TbUser.DoesNotExist: return username raise forms.ValidationError(self.error_messages['duplicate_username']) class Meta(UserCreationForm.Meta): model = TbUser class SignUpForm(CustomUserCreationForm): email = forms.EmailField() customer_id = forms.CharField(label="Customer ID") def clean_username(self): data = self.cleaned_data['username'] if TbUser.objects.filter(username=data).exists(): raise forms.ValidationError( "Username already exists. Pick another one") def clean(self): cd = self.cleaned_data password1 = cd.get("password1") password2 = cd.get("password2") if password1 != password2: raise ValidationError("Passwords did not match") return cd class Meta: model = TbUser fields = ['username', 'email', 'real_name', 'customer_id', 'password1', 'password2'] -
Create a dropdown select based on a first selected dropdown in DJango/Ajax
I'd like to create a dropdown select based in a first selected dropdown using Ajax/JQuery with Django I alread make a couple of tests, but without success for now: Models: class MaintenanceEquipment(models.Model): equip_id = models.CharField(max_length=30, auto_created=False, primary_key=True) line_nm = models.CharField(max_length=20, blank=True, null = True) sequence = models.CharField(max_length=30, blank=True, null = True) equip_model = models.CharField(max_length=30, blank=True, null = True) def __str__(self): return self.equip_id views: from django.shortcuts import render from maintenance.models import MaintenanceEquipment def maintenanceIssueView(request): equipment_list = MaintenanceEquipment.objects.all() context = {'equipment_list':equipment_list} return render(request, 'maintenance/maintenanceIssue.html', context) def load_equipment(request): if request.method == 'GET': line = request.GET.get('line_nm') equipment = MaintenanceEquipment.objects.filter(line_nm=line) context = {'equipment': equipment} return render(request, 'maintenance/maintenanceIssue.html', context) maintenanceIssue.html: <form method="POST" id="maintenanceForm" data-equipment-url="{% url 'ajax_load_equipment' %}" novalidate> {% csrf_token %} <div style="text-align:left;" class="container-fluid"> <div style="text-align:left;" class="form-row"> <div class="form-group col-md-6"> <label for="line_nm" style="font-size:medium;">Line</label> <select class="form-control" id="line_nm" name="line_nm" > {% for instance in equipment_list %} <option id="{{ instance.line_nm }}" value="{{ instance.line_nm }}">{{ instance.line_nm }}</option> {% endfor %} </select> </div> <div class="form-group col-md-6"> <label for="equip_sequence" style="font-size:medium;">Machine</label> <select class="form-control" id="equip_sequence" name="equip_sequence"> {% for instance in equipment %} <option id="{{ instance.equip_id }}" value="{{ instance.sequence }}">{{ instance.sequence }}</option> {% endfor %} </select> </div> </div> </div> </form> <script> $("#line_nm").change(function () { var url = $("#maintenanceForm").attr("data-equipment-url"); var lineID = $(this).val(); $.ajax({ url: url, … -
Sending data to sqlite3 with django
I want to send data to Sqlite3 with Django. What do you need to learn for this? And how can I do? Can you explain simply? My goal: to make a registration system. It can be used on multiple computers. Likewise, the registration process will be via CMD. Sending the information will be through the Django framework. -
Django/Celery 'Received unregistered task of type'
I have hit a brick wall for quite some time with my simple task that I need to run asynchronously from a Django server. I have a form on a page that when I submit a value my views.py executes a simple multiplication function from the tasks2.py file which also has my Celery stuff. With Celery running by this command from my terminal: celery -A tasks2 worker -l info -P eventlet And submitting a number "2 in this case" through my form I get the following error Received unregistered task of type 'app_scrape.tasks2.my_multiply'. The message has been ignored and discarded. Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[["2"], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (80b) Traceback (most recent call last): null}]' (80b) File "c:\users\likea\.virtualenvs\django-j1eue__k\lib\site-packages\celery\worker\consumer\consumer.py", line 581, in on_task_received ry\worker\consumer\consumer.py", line 581, in on_task_received strategy = strategies[type_] KeyError: 'app_scrape.tasks2.my_multiply' Project structure: - src-estategy - manage.py - app_scrape - views.py - tasks2.py - models.py - .... - proj_estategy - __init__.py - settings.py - urls.py - .... tasks2.py from celery import Celery app = Celery('tasks2', broker='amqps://mcbojxac:6sC7n38IdqmNoNgUjmjBkHum6RxRnaqt@clam.rmq.cloudamqp.com/mcbojxac', backend='db+postgresql://kbsrjinigbkzqu:ed0aab74c997b56aa756d510439e28404cf1e87de629a7af66bd49ae29961bbb@ec2-44-195-201-3.compute-1.amazonaws.com/d85tdjbd3am2sc') @app.task def my_multiply(x): print(x) return x ``` **views.py** ``` #Django … -
How to pass a nested foreignkey object to a another model?
I've been stumped for days; hoping one of you wizards can get me out of this pickle.. I have a model called ExtraSlot class ExtraSlot(models.Model): ....... employee = models.ForeignKey(Employee, on_delete = models.CASCADE, related_name="employee") this is the serializer class ExtraSlotSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(many=True) <-- If I add this it tries to iterate through and errors out class Meta: model = WorkingSlot fields = (..... 'employee') fields = ('__all__') <- also used this to no avail depth = 3 I'm trying to add an Employee to the model; in the admin panel it is fine. The employee object can be selected. The DRF api doesn't show anything; I've read HTML list input isn't supported which is fine but the employee field as an input (even in raw format) doesn't show at all. Employee extends User (AbstractBaseUser) - here is the list error if I try many=true and passing the entire serializer. TypeError: 'Employee' object is not iterable (if I try pass EmployeeSerializer with many=True; which makes sense.) employee = EmployeeSerialzer() - passes the entire object as if I want to create a new one?! I want to allow a user to sign employee to the extraslot. Please help! -
DateField's DateInput widget with 'format="%B"' is not localized/translated
I'm trying to display a form-field with full month + Year representation (like 'December 2021') but I cannot localize it to German. In forms.py I'm using format("%B %Y") in the widget to achieve that representation, like so: date = DateField(widget=DateInput(attrs={"autocomplete": "off"}, format="%B %Y")) I'm using this form in an UpdateView, nothing fancy... <div class="form-row"> ... some fields <div class="form-group flatpickrdatetimeinput col-md-6 mb-0"> {{ form.date|as_crispy_field }} </div> </div> The date representation works in terms of Month + Year, but I need to localize the month name (December -> Dezember). I cannot find the error, I tried changing the field attribute (localize=True) and also I have played around with the settings (i18n, l10n, etc) with no success. In fact, the settings have worked out so far. In the same template I am using the 'date' template filter and it translates the month just fine <h2>{{campaign.date | date:'F Y' }}</h2> -
First posts of all the users
I am building a BlogApp and I am trying to implement a feature , So, I am trying to access first post of all the users. models.py class BlogPost(models.Model): user= models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30, default='') body = models.CharField(max_length=30, default='') views.py def first_posts(request): user = User.objects.all() posts = BlogPost.objects.filter(user=user).first() context = {'posts':posts} return render(request, 'first_posts.html', context) But it is showing The QuerySet value for an exact lookup must be limited to one result using slicing. When i try to use User.objects.all().first() then it is only showing first post in all posts. I have tried many times But it is still not working. Any help would be much Appreciated. Thank You -
How do I write a view function for exporting a filtered data to an excel file in Django?
I have a model which has five ForeignKey fields, which basically works a master data comprising of almost all the models. class IpdReport(models.Model): patient=models.ForeignKey(Patient, on_delete=CASCADE) package=models.ForeignKey(Package, on_delete=CASCADE) receivables=models.ForeignKey(Receivables, on_delete=CASCADE, blank=True, null=True) discharge=models.ForeignKey(Discharge, on_delete=CASCADE, blank=True, null=True) realization=models.ForeignKey(Realization, on_delete=CASCADE, blank=True, null=True) @property def track_id(self): ...... Its view is like: def ipd_report_view(request): report=IpdReport.objects.all() print(report[0].patient.name) total1=report.aggregate(Sum('realization__amount_received')) total2=report.aggregate(Sum('realization__deficit_or_surplus_amount')) context={'report': report, 'total1':total1, 'total2':total2} return render(request, 'account/ipdreport.html', context) Its Template: <body> <table class="design"> <h3>Track Report</h3> <th class="design">ID</th> <th class="design">Name</th> <th class="design">Patient Number</th> <th class="design">MR/UID</th> <th class="design">Diagnosis</th> <th class="design">Treatment Type</th> <th class="design">Type of Patient</th> <th class="design">Date of Admission</th> <th class="design">Max Fractions</th> <th class="design">Total Package</th> <th class="design">RT Number</th> <th class="design">Discount</th> <th class="design">Approved Package</th> <th class="design">Proposed Fractions</th> <th class="design">Done Fractions</th> <th class="design">Base Value</th> <th class="design">Expected Value</th> <th class="design">Date of Discharge</th> <th class="design">Mould Charges</th> <th class="design">CT Charges</th> <th class="design">Amount Received</th> <th class="design">Billing Month</th> <th class="design">Deficit or Surplus Amount</th> <th class="design">Deficit Percentage</th> <th class="design">Surplus Percentage</th> <th class="design">Action</th> {% for rp in report %} <tr class="design"> <td class="design">{{rp.track_id}}</td> <td class="design">{{rp.patient.title.title}}{{rp.patient.name}}</td> <td class="design">{{rp.patient.patient_number}}</td> <td class="design">{{rp.patient.mr_uid}}</td> <td class="design">{{rp.package.diagnosis}}</td> <td class="design">{{rp.package.treatment}}</td> <td class="design">{{rp.package.patient_type}}</td> <td class="design">{{rp.package.date_of_admission}}</td> <td class="design">{{rp.package.max_fractions}}</td> <td class="design">{{rp.package.total_package}}</td> <td class="design">{{rp.receivables.rt_number}}</td> <td class="design">{{rp.receivables.discount}}</td> <td class="design">{{rp.receivables.approved_package}}</td> <td class="design">{{rp.receivables.proposed_fractions}}</td> <td class="design">{{rp.receivables.done_fractions}}</td> <td class="design">{{rp.receivables.base_value}}</td> <td class="design">{{rp.receivables.expected_value}}</td> <td class="design">{{rp.discharge.date_of_discharge}}</td> <td class="design">{{rp.discharge.mould_charges}}</td> <td class="design">{{rp.discharge.ct_charges}}</td> <td class="design">{{rp.realization.amount_received}}</td> <td class="design">{{rp.realization.billing_month}}</td> <td class="design">{{rp.realization.deficit_or_surplus_amount}}</td> <td … -
Why css don't loaded in django?
I encountered a problem. Just my .html, the css files not loaded,even I write the absolute path which can be visited from the browser as follows: <link ref="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}" /> <link ref="stylesheet" type="text/css" href="http://127.0.0.1:8000/static/css/bootstrap.min.css" /> Could anyone please help me? My PyCharm project location: E:\workspaces\workspace-py\python-test django project relative lication: \django\djangotest \template\base.html: <!DOCTYPE html> <html lang="en"> {% load static %} <head> <meta charset="UTF-8"> <title></title> <link ref="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}" /> <link ref="stylesheet" type="text/css" href="{% static 'css/index.css' %}"/> \static\css\bootstrap.min.css \djangotest\settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), ) -
How to trigger a function at regular times?
I have a DashboardData model. I get some info from this form and according to the given answers, I run a function by using form answers as parameters. This is my form model: class DashboardData(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) # request.user n_username = models.CharField(max_length=250) n_password = models.CharField(max_length=250) n_url = models.CharField(max_length=250) n_port = models.IntegerField() period = models.CharField(max_length=250) db_password = models.CharField(max_length=250, null=True) And this is my function: class myFunction(): def __init__(self, n_user, n_password, n_url, n_port, db_password): self.zaman = datetime.now().strftime("%Y-%m-%d") self.location = a_url self.static_fields = {} self.index_name = "vulns-" + self.zaman self.download_all(n_user, n_password, n_url, n_port, db_password) self.send_it() I want to run this function like functions.myFunction(n_user, n_password, n_url, n_port, db_password) with user's DashboardData values every 15 minutes. How can I do it? I tried to use apscheduler app but I cannot run it. -
Question regarding a Django web app with firebase storage and heroku for deployment
I've made a wallpaper generator website that also lets users share wallpapers, memes nd stuff, im using my sqlite db to store credentials of created users and then use firebase storage to upload their images (using pyrebase4) , while the image url gets retrieved and is stored in the sqlite3 db. I just have two questions. Question 1: my first question is when i will launch the website using heroku, do i need to set some enviroment variable or something for it to work? like i know we have to do something like that for aws, and your secret key etc.. do i need to do some extra stuff so that it can work?? Question 2 : So while the user is logged in my website, he already is authenticated by django...so when he uploads an image he/she doesnt know what's going behind the scenes...but im uploading their image to firebase...so currently in test mode im doing this without authenticating anyone...but in production how im going to do that? do i have to authenticate them with fireabse as well? can i just let anyone upload a file their as long as they are logged in my website?? which will obv … -
When using Django's Default Storage should/can you close() an opened file?
When using Django's DefaultStorage it's possible to open and read a file something like this: from django.core.files.storage import default_storage file = default_storage.open("dir/file.txt", mode="rb") data = file.read() When using python's own open() method, it's best to close() the file afterwards, or use a with open("dir/file.txt") as file: construction. But reading the docs for Django's Storage classes, and browsing the source, I don't see a close() equivalent. So my questions are: Should a file opened with Django's Default Storage be closed? If so, how? If not, why isn't it necessary? -
formset django, problems saving a lot of data added to the click
Hi everyone I have a problem with django formset.I can create through js adding objects but at the moment of creation I only save the first object I created and not the others. I beg you for months that I have been on this thing without finding a real solution. below I put my code, I hope you are reading that you can help me, I will be grateful. HTML <section class="container mt-3"> <div class="d-flex align-items-center justify-content-between"> <h1 class="nome-scheda">TEST FORMSET</h1> <a href="{% url 'lista' %}" class="btn btn-outline-dark">LISTA</a> </div> <hr> <form method="post"> {% csrf_token %} {{ formset.management_form }} <div class="list-form"> {% for form in formset %} <div class="esercizio-box"> {{ form.as_p }} </div> {% endfor %} </div> <div id="form-vuoto" class="hidden"> <div class="esercizio-box"> {{ formset.empty_form.as_p }} </div> </div> <div class="text-end mt-2 mb-5"> <button id="add" type="button" class="btn btn-success">AGGIUNGI</button> </div> <input type="submit" class="btn btn-primary" style="width:100%;" value="crea"> </form> </section> SCRIPT <script> $('#add').click(function(){ var form_idx = $('#id_form-TOTAL_FORMS').val(); $('.list-form').append($('#form-vuoto').html().replace(/__prefix__/g, form_idx)); $('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1); }); </script> VIEWS.PY from django.forms import formset_factory def testViews(request): testFormSet = formset_factory(testForm, extra=0) if request.method == "POST": formset = testFormSet(request.POST) if formset.is_valid(): for form in formset: form.save() return redirect('/lista/') else: formset = testFormSet() context = {'formset': formset} return render(request, "tests.html", context) -
Error __str__ returned non-string (type NoneType)
I know that this error is classic. But I'm facing a harder problem : This is my model. I've check all the topics about this common problem, try to resolve it but I don't achieved. I cannot add stafftimeslot in the admin panel. Can you help me ? Here is my models.py : from django.db import models from django.utils import timezone from staffs.models import Staff from students.models import Student TIMESLOT_LIST = ( (0, '09:00 – 09:30'), (1, '09:30 – 10:00'), (2, '10:00 – 10:30'), (3, '10:30 – 11:00'), ... ) class StaffTimeSlots(models.Model): staff = models.ForeignKey(Staff, null=True, on_delete=models.CASCADE) date = models.DateField(default=timezone.now) time_slot = models.CharField(max_length=2, choices=TIMESLOT_LIST) def get_absolute_url(self): return reverse('stafftimeslot_detail', kwargs={"pk": self.pk}) def __str__(self): return str(self.date) EDIT : When I delete ForeignKey, it works but when I reuse it, it does not work anymore. So I tried to replace with OnetoOneField and ManytoManyField and I have faced with the same problem. It seems that the model does not accept model relations. How can I do to relate this model with the Staff model with a foreign key ? -
Wie kann ich die Adminseite nochmal zeigen? [closed]
als ich mit mssql verbindet habe, kommt zu mir diese Fehle -
(Django) how to submit a form with empty fields?
I have a form with a drop down list with two options ("MCQ" and "SEQ") and some fields. Selecting "MCQ" would hide fields used by "SEQ" and vice versa. I want to submit this form but the "please filled out this field" notice pops up. What should I do to submit this form? I've searched around Stack overflow before looking possible solutions, some suggested placing "required" or "disabled" beforehand, however I would like a dynamic way of doing if possible but based it on which option the user selects since the user might leave everything empty and just submit if nothing is required. Additional Information: I'm using forms.ModelForm, the fields came from there. I'm using js to hide and show the relevant fields. I Appreciate any help/suggestions. :) -
django.core.exceptions.ImproperlyConfigured: Field name `operatives` is not valid for model `Operative`
field raise ImproperlyConfigured( [14/Sep/2021 10:46:30] "POST /operatives/ HTTP/1.1" 500 133558 -
Unable to override the pre-authenticate and authenticate methods in adapters
Unlike save_user and send_email in DefaultAccountAdapter, I am unable to override the pre_authenticate and authenticate methods. Please can someone explain why or how I can achieve these? class DefaultAccountAdapterCustom(DefaultAccountAdapter): def pre_authenticate(self, request, **credentials): # Do something before authenticating def authenticate(self, request, **credentials): # Do something after authenticating -
Can't use getList() with a MultiValueDict
I am uploading images using Axios/Next.JS/Django, and I am appending 4 images to form data. When I print(request.FILES) I get <MultiValueDict: {'images': [<InMemoryUploadedFile: HARRY-POTTER-HERMIONE-GRANGER-MAGIC-WAND__0082686381314-Z.JPG (image/jpeg)>, <InMemoryUploadedFile: harry-potter-wand-gringotts.jpeg (image/jpeg)>, <InMemoryUploadedFile: HarryPotterWandNN8415.jpeg (image/jpeg)>, <InMemoryUploadedFile: Hgwand.webp (image/webp)>]}> Which is correct, but when I go to loop through the data (request.FILES.getList('images')) to save it to an S3 bucket I get the error: AttributeError: 'MultiValueDict' object has no attribute 'getList'. Everything I've seen on SO and other places are telling me to use getList(). Am I missing something here? -
Django - How can my asgi websocket path be on my swagger
I am creating an api where two endpoints are using the ws(s) protocol. As my API is behind Google endpoint, Every endpoint needs to be defined onto an OpenApi2.0 file. To create this definition I use drf-yasg. I have a routing. py file like this: """ systems/routing.py""" from django.urls import path from .consumers.list_sessions_consumer import MyFirstConsumer from .consumers.session_consumer import MySecondConsumer urlpatterns = [ path(r'v1/ws/yo/<str:uuid>/sessions-sumpup', MyFirstConsumer.as_asgi()), path(r'v1/ws/yo/<str:uuid>/sessions', MySecondConsumer.as_asgi()), ] and I register it onto my asgi.py file like this: # pylint: skip-file """ main/asgi.py """ import os import django from django.core.asgi import get_asgi_application django_asgi_app = get_asgi_application() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') django.setup() from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from systems.websockets.routing import urlpatterns as system_websocket_url application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter( system_websocket_url ) ), }) Don't mind the import order this is due to this error: Django apps aren't loaded yet when using asgi So my socket works as expected, now, I want my command line: python3 manage.py generate_swagger swagger.yaml to add these new endpoint to my swagger file. I tried to directly add my url to the same object then all my other urls like so: urlpatterns = [ path(r'v1/toto/<str:uuid>', MyView.as_view()), ..., path(r'v1/ws/yo/<str:uuid>/sessions-sumpup', MyFirstConsumer.as_asgi()), path(r'v1/ws/yo/<str:uuid>/sessions', MySecondConsumer.as_asgi()), ] But nothing shows … -
Adding support for Alpine.js to a Django package
I'm using a package that adds an SVG template tag to inline my SVGs in my Django templates. I forked the project and added support for passing HTML attributes to SVG. So, right now I'm able to use it as the following: {% load svg %} <a class="font-semibold text-gray-850 href="#0"> {% svg 'icon-chevron-down' class="inline -mb-0.5 w-4 h-4 ml-0.5 transition-transform duration-200 transform fill-current text-gray-400" %} </a> But I'm encountering a problem when I want to use Alpine.js within the svg. I'd like to be able to do something like this: {% svg 'icon-chevron-down' :class="{'rotate-180': open, 'rotate-0': !open}" class="inline -mb-0.5 w-4 h-4 ml-0.5 transition-transform duration-200 transform fill-current text-gray-400" %} How can I make it work? The repo to my package: https://github.com/xshapira/django-simple-svg svg.py from __future__ import absolute_import import logging import os from django import template from django.conf import settings from django.contrib.staticfiles import finders from django.core.exceptions import ImproperlyConfigured from django.utils.safestring import mark_safe from simple_svg.exceptions import SVGNotFound logger = logging.getLogger(__name__) register = template.Library() @register.simple_tag def svg(filename, *args, **kwargs): SVG_DIRS = getattr(settings, "SVG_DIRS", []) if type(SVG_DIRS) != list: raise ImproperlyConfigured("SVG_DIRS setting must be a list") path = None if SVG_DIRS: for directory in SVG_DIRS: svg_path = os.path.join( directory, "{filename}.svg".format(filename=filename) ) if os.path.isfile(svg_path): path = svg_path else: … -
Is there a way to pass information between pages in Reactjs using navlink?
I am using a Django REST framework, storing data in a model. I am then using Reactjs to consume the API and make GET/POST requests. Inside the React frontend, I am using react-router-dom to navigate between pages. I want to be able to click on a specific link, but then also pass on information to the component towards which the link is routed. This is my index.js code import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import { BrowserRouter } from 'react-router-dom'; ReactDOM.render( <BrowserRouter> <App/> </BrowserRouter>, document.getElementById('root') ); This is my App.js code import './App.css'; import Container from '@material-ui/core/Container'; import Navigation from './Components/ToolBar' import Main from './Components/Main' function App() { return ( <> <Container maxWidth='lg' className="App"> <Navigation/> <Main/> </Container> </> ) } export default App; This is my Main.js code import { Switch, Route } from 'react-router-dom'; import Projects from './Projects'; import Tickets from './Tickets'; const Main = () => ( <Switch> <Route exact path='/projects' component={Projects}></Route> <Route exact path='/tickets' component={Tickets}></Route> </Switch> ); export default Main; This is my Toolbar.js code, which is used for navigating to different pages import { Button } from '@material-ui/core' import AppBar from '@material-ui/core/AppBar' import Toolbar … -
Parameterised decorator returning an error
I'm writing a decorator to check a certain attribute of a user. I will use this decorator over POST of GET methods of some class based APIs. The attribute is stored in the request.session["user_status']. def decorator_func(func): def wrapper_func(class_reference, request): status = request.session["user_status"] if status != value1 or status != value2: return Response(data="A dictionary") return func(class_reference, request) return wrapper_func Whenever the if condition is not satisfied and the func is accessed, it works as expected. But when the condition is satisfied and the Response() is returned, I'm getting following error: TypeError at "api path on which the decorator is applied" Object of type "custom user model of this project" is not JSON serializable I'm guessing due to not writing the decorator in the correct way I'm getting some error and when it is trying to return the error, it's also trying to return the current user object which is not JSON serializable. The user object is also stored in request.session["user"]. What am I doing wrong in this parameterized decorator function?