Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update Django url with javascript
So i tried to update a url with javascript like follows: unction updateUrl() { var docs = document.getElementById('arztAMA'); var doctor = docs.value; console.log(doctor); var m = document.getElementById('monatAMA'); var month = m.value; console.log(month); var url = "{% url 'doctormonthbilling' month=123456 doctor=123 %}".replace(123456,doctor.toString()).replace(123,month.toString()); console.log(url); var button = document.getElementById('docmonthbill'); button.href = url; } but it doesn't work! I get: Reverse for 'doctormonthbilling' with keyword arguments '{'month': 123456, 'doctor': 123}' not found. 1 pattern(s) tried: ['doctormonthbilling/(?P<month>[^/]+)/(?P<doctorid>[^/]+)$'] How can i update the urls? is there any way to do it? -
How to load a parameter from an object in an object?
class Product(models.Model): subcategory = models.ManyToManyField(Subcategory, related_name="Category") name = models.CharField(max_length=32, unique=True) title = models.CharField(max_length=3000) ean = models.PositiveIntegerField(blank=True, null=True, unique=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True, null=True) origin_name = models.CharField(max_length=32, blank=True, null=True) quantity = models.PositiveIntegerField(blank=True, null=True) highlights = models.TextField(max_length=3000, blank=True, null=True) description = models.TextField(max_length=3000, blank=True, null=True) delivery = models.TextField(max_length=3000, blank=True, null=True) selling_price = models.DecimalField(max_digits=9, decimal_places=2) slug = models.SlugField(unique=True) class Infobox(models.Model): name = models.CharField(max_length=32) measurment = models.CharField(max_length=32) resolution = models.CharField(max_length=32) product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) I would like to display on my detail page all infobox objects that are linked to the device, do any of you know how to do this? THANKSSSS <3 -
PieChar inside for loop tag html django
I am facing this challenge of creating multiple pieChart plot in my html page. I have a for loop in the page and I want to plot the data. I just insert the script inside the loop but it doesn't work. the code is: {% for welTsts in WellTsTProDChart %} <div class="container"> <div class="row"> <div class="col-lg-6"> </div></div> <div class="col-lg-6"> <div class="card card-success"> <div class="card-header"> <h3 class="card-title">Production Tests: {{ welTsts.TestDate }} Oil {{ welTsts.TestOIL}} (m3/D)</h3> </div> <div class="card-body w3-light-grey solid"> <canvas id="pieChart" style="min-height: 230px; height: 230px; max-height: 245px; max-width: 100%;"</canvas> {% block custom_js %} <script> $(document).ready(function(){ //Data Set for PIE CHart var pieData = { labels: [ 'OIl', 'Water' ], datasets: [ { data: [{{ welTsts.TestOIL}} , {{ welTsts.TestWtr}}], backgroundColor : ['#00a65a', '#5088f1'], } ] } var pieChartCanvas = $('#pieChart').get(0).getContext('2d') var pieOptions = { maintainAspectRatio : false, responsive : true, } //Create pie or douhnut chart // You can switch between pie and douhnut using the method below. var pieChart = new Chart(pieChartCanvas, { type: 'pie', data: pieData, options: pieOptions }) }) </script> {% endblock custom_js %} </div></div></div></div></div> {% endfor %} when I have just one data it doesn't know the variables (data: [{{ welTsts.TestOIL}} , {{ welTsts.TestWtr}}]) and if I … -
Collectstatic seems to be working, but is not actually copying files to desired folder on Heroku
So I've been reading a lot of similar issues, but haven't found an exact match. I'm deploying my django production app in Heroku with uwsgi and whitenoise. So far I've set everything to its defaults. settings.py ... MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', ... ] ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] ... uwsgi.ini [uwsgi] http-socket = :$(PORT) master = true env DJANGO_SETTINGS_MODULE=myProject.settings die-on-term = true processes = 4 module = myProject.wsgi:application memory-report = true ./manage.py collectstatic works locally and runs with debug mode set to false. The same command also works in heroku, hits me with 194 static files copied to '/app/staticfiles', 1 unmodified, 617 post-processed BUT the copied files do not show up in the corresponding folder when I tunnel to heroku with heroku ps:exec. Also when trying to connect to the website, ValueError is raised, as the files are not found. -
The view bonet.decorators.wrapper_func didn't return an HttpResponse object. It returned None instead
error at loading profileError Error The view bonet.decorators.wrapper_func didn't return an HttpResponse object. It returned None instead Hii!! I'm new to stackoverflow and I'm getting this error and I'm not getting proper solution for this so plzz help me out to get out of this error My view.py @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def profile(request): return render(request, 'bonet/profile.html') @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def account_settings(request): customer = request.user.customer form = CustomerForm(instance=customer) if request.method == 'POST': form = CustomerForm(request.POST, request.FILES,instance=customer) if form.is_valid(): form.save() context = {'form':form} return render(request, 'bonet/account_settings.html', context) -
how can I use django to adjust the type in an input field
I try to create an automatic individual input mask with django and bootstrap. My goal is that I only need to change the forms.py and that the mask adapts itself. I know that django can create standard masks from forms.py, but unfortunately they are a bit ugly For example, I have the form class: class PersonForm(forms.ModelForm): m_firstname = forms.CharField(label='firstname ') m_lastname = forms.CharField(label='lastname ') m_email = forms.EmailField(label='email') m_birthday = forms.DateField(label='birthday ') class Meta: model = Person fields = ['m_firstname', 'm_lastname', 'm_birthday', 'm_email'] labels = { 'm_firstname': 'firstname', 'm_lastname': 'lastname', 'm_birthday': 'birthday', 'm_email': 'email'} and create the html code from it: {% for field in UserForm.visible_fields %} <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text">{{ field.label_tag }}</span> </div> <input type="text" class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default" id={{ field.name }} name={{ field.name }}> </div> {% endfor %} that works very well, now i want to set the type of the input to date for the birthday. I need another handover: so I can write something like this: <input type={{ field.type }} class="form-control" aria-label="Default" aria-describedby="inputGroup-sizing-default" id={{ field.name }} name={{ field.name }}> unfortunately my approaches have not worked so far. I thought maybe to use the widgets and if necessary to query them with an if statement, but … -
Django process file before saving
I want to be able to process a file before saving in Django. I wanted to do it in a way that would affect both default Django (like through admin interface) and DRF (which uses the create method in the serializer). So I tried to overwrite the save method as below: class Soundbite(models.Model): app_label = 'soundbite' name = models.CharField('name', max_length=32, null=False) audio = models.FileField('audio', upload_to='soundbites', null=False, validators=[FileExtensionValidator(['mp3', 'wav', 'aac'])]) duration = models.FloatField('duration', null=False, blank=True)blank=True) def save(self, *args, **kwargs): if not self.duration: storage: FileSystemStorage = self.audio.storage file = self.audio # process file, like get duration using ffmpeg and validate its a proper audio file. info = probe(storage.path(self.audio.name)) duration = info['format']['duration'] print(duration) self.duration = duration super().save(*args, **kwargs) # Call the "real" save() method. But I don't exactly know how to access the file before calling the super save method. I can do it either by having a filesystem path with the file, or by reading the raw bytes of the file. How would I access the file before saving to database? -
Create a new table in the view.py in Django
In the document, I can define a table in the models.py. from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) Run python manage.py makemigrations and python manage.py migrate to create a new table in the database. If I want to create a new table when do something in the views.py, is it possible? For example, I want create a personal table for some new member when he/she register a new account. -
How to store GDAL objects in a geodjango Geometry object?
I have a GeoDjango GeometryField in my database: class Place(models.Model): name = CharField() geometry = models.GeometryField() I'm trying to load certain parts of shapefiles into my database. from django.contrib.gis.gdal import DataSource datasource = DataSource("file.shp") layer = datasource[0] for each in layer: name = each.get("NAME") # To obtain the name ... (some more logic to add properties and validate which objects should be imported) Place.objects.create( name = name, geometry = each.geom ) However, this returns this error: Cannot set Place SpatialProxy (GEOMETRY) with value of type: <class 'django.contrib.gis.gdal.geometries.MultiPolygon'> I'm not sure exactly how I have to transform this gdal.geometries.MultiPolygon object so that it can be stored in the database. I've tried using: from django.contrib.gis.gdal import OGRGeometry geometry = OGRGeometry(each.geom) But this won't work. -
'static''. Did you forget to register or load this tag? [closed]
enter image description here enter image description here Ive Even Got The Urls Correct Idk Whats Wrong ive doubled checked everything -
why the guniron.sock file is not getting created at all and throwing error?
First of all, I have seen tons of documents in stackoverflow as well as other blogs. But nothing seems to be working for me. I have hosted a django based web application. I have followed the link django deployment, I have applied almost everything that is mentioned in the document, everything was going fine until I came to the point where I had to configure gunicorn. I a not working in the python virtual environment. However, almost every solution across the various platform only talks about gunicorn configuration in virtual environment. So should I assume that gunicorn doesn't work without virtual environment? As per my understanding from the document and my current application directory path. I have below gunicorn.services [Unit] Description=gunicorn daemon #Requires=gunicorn.socket After=network.target [Service] User=root Group=root WorkingDirectory=/home/abc/our_website/project_name ExecStart=/usr/local/bin/gunicorn --access-logfile /home/abc/logs/gunicorn_access.log --error-logfile /home/abc/logs/gunicorn_error.log --workers 3 --bind unix:/home/abc/run/gunicorn.sock project.wsgi:application [Install] WantedBy=multi-user.target and below is my nginx server details: server { listen 80; server_name mydomain.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/abc/our_website/project_dir; } location / { include proxy_params; proxy_pass http://unix:/home/abc/our_website/project_dir/project.sock; #proxy_pass http://unix:/home/abc/run/gunicorn.sock } } However, the gunicorn service not coming up. I am getting below errors: /var/log/nginx/error.log *22 connect() to unix:/home/abc/our_website/project_dir/project.sock failed (2: No such … -
Python Django - how to handle blob data post by Ajax from client?
I have a trouble with python django. On client i created a list blob from capture camera to image then post by ajax. On server i want get list blob (image) and upload to AWS then return path to save into my Database. in template var formData = new FormData(this); if (blob_arr.length > 0) { for (var i = 0; i < blob_arr.length; i++) { formData.append('img_taked_' + i.toString(), blob_arr[i]); } } $.ajax({ url: $(this).attr("action"), type: 'POST', data: formData, mimeType: "multipart/form-data", contentType: false, cache: false, processData: false, success: function (response) { //var data = JSON.parse(response); console.log(response); }, error: function (error) { console.log(error); } }); in views img_1 = request.FILES.get('img_taked_1') print ('DEBUG:>', img_1, type(img_1)) print output is DEBUG:> blob <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> i want save that blob to a image for send it to AWS, how ? -
Set choices as same model Fields in django model?
In quiz app Question modal has fields like question_text, Option_1, Option_2, Option_3, And Correct_ans. So I want to add that correct_ans has choice based on data entered in the Options fields. I cant understand how to set it. plzz help. -
CreateView error NOT NULL constraint failed: members_experience.CustomUser_id
Hi i have a CustomUser model, a user can have one to many Experinces. The thing is that i want to use the CreateView on Experience and get the instance of CustomUser. When i try to post the form i get a error message NOT NULL constraint failed: members_experience.CustomUser_id. I can solve this whit a InlineFormSet but that is not what i want in this case. Im new to Django, any tips? thx Model Table 1 CustomUser: Class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Epost'), unique=True,) personal_Id = models.CharField(_('Personnummer'),max_length=12, blank=False) first_name = models.CharField(_('Förnam'), max_length=30, blank=True) middle_name = models.CharField('Mellannamn', max_length=30, blank=True) last_name = models.CharField(_('Efternamn'), max_length=30, blank=True) table 2 Experience class Experience(models.Model): CustomUser = models.ForeignKey(CustomUser, on_delete=models.CASCADE) title = models.CharField(_('Beskrivning'), max_length=200) job_type = models.CharField(_('Arbetsform'), max_length=10, choices=JOB_TYPES) porfession = models.CharField(_('Yrke'), max_length=10, choices=PROFESSION_LIST) posted_on = models.DateTimeField(_('Registrerad'), auto_now_add=True) updated_on = models.DateTimeField(_('Senast uppdaterad'), auto_now=True) years_of_exp = models.CharField(_('Erfarenhet'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True) URL path('<int:pk>/experienceadd/', views.ExperienceCreate.as_view(), name='ExperienceCreate'), View class ExperienceCreate(CreateView): model = Experience template_name = 'members/experience_create_form.html' success_url = reverse_lazy('MemberIndex') fields = ['title', 'job_type', 'porfession', 'years_of_exp'] Template <form method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save"> </form> -
Django + Stripe , how to add address field in Stripe checkout page ,
I have integrated Django with Stripe. After I submit the card details in the frontend , it gives below error InvalidRequestError at /api/ChargeView/ As per Indian regulations, export transactions require a customer name and address. More info here: https://stripe.com/docs/india-exports How can I ask the customers to fill the address in the checkout page ? If the customers billing address exists, how can I pass it to checkout page ? VIEWS.PY class HomeView(TemplateView): template_name = 'backend/index1.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['key'] = settings.STRIPE_PUBLISHABLE_KEY return context class ChargeView(TemplateView): def post(self, request): charge = stripe.Charge.create( amount=100, currency='GBP', description='Hat purchase.', source=request.POST['stripeToken'] ) return HttpResponse('<p>Thank you for your payment!</p>') CHECK OUT PAGE <form action="{% url 'payments-charge' %}" method="POST"> {% csrf_token %} <script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="{{ key }}" data-description="You are purchasing: Hat from this site." data-amount="100" data-currency="gbp" data-locale="auto" ></script> </form> The possible error location is the ChargeView section. I have installed the Stripe app with Django and configured the test keys. -
Importing Pyside-2 project into my web site built by Django
I have a UI project by Pyside 2 in python. Also I have a web site built base on Django. I want to know if it is possible to run my UI project in the web site? Is there a way to convert the UI code into Html or just a simple way to put my UI code in HTML file? -
if model._meta.abstract: AttributeError: type object 'ProductObject' has no attribute '_meta'
I want to add one of my models to the admin panel, but this error falls: > Traceback (most recent call last): File > "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\threading.py", > line 932, in _bootstrap_inner > self.run() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\threading.py", > line 870, in run > self._target(*self._args, **self._kwargs) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", > line 53, in wrapper > fn(*args, **kwargs) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", > line 109, in inner_run > autoreload.raise_last_exception() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", > line 76, in raise_last_exception > raise _exception[1] File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", > line 357, in execute > autoreload.check_errors(django.setup)() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", > line 53, in wrapper > fn(*args, **kwargs) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\__init__.py", > line 24, in setup > apps.populate(settings.INSTALLED_APPS) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", > line 122, in populate > app_config.ready() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\apps.py", > line 24, in ready > self.module.autodiscover() File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\admin\__init__.py", > line 26, in autodiscover > autodiscover_modules('admin', register_to=site) File "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\module_loading.py", > line 47, in autodiscover_modules > import_module('%s.%s' % (app_config.name, module_to_search)) File > "C:\Users\smirn\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", > line 127, in import_module > return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File > "<frozen importlib._bootstrap>", line 991, in _find_and_load File > "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked > File "<frozen importlib._bootstrap>", line 671, in _load_unlocked > File "<frozen importlib._bootstrap_external>", line 783, in > exec_module File "<frozen importlib._bootstrap>", line 219, in > _call_with_frames_removed … -
Adding assigner and assignee in Django
I am fairly new to django rest framework, and I am trying to make a model which is associated with two users, one as assigner and the other as assignee. I tried adding two different foreign keys, but it throws error. Here is my code: job = models.ForeignKey(Job,related_name='Job',on_delete=models.CASCADE, null=True) assigner = models.ForeignKey(User, on_delete=models.PROTECT, null=True) assignee = models.ForeignKey(User, on_delete=models.PROTECT, null=True) unit = models.ForeignKey(Unit,related_name='UnitName',on_delete=models.CASCADE, null=True) equipment = models.ForeignKey(Equipment,related_name='EquipmentName',on_delete=models.CASCADE, null=True) name = models.CharField(max_length=200) category = models.CharField(max_length=200, null=True,blank=True) start_date = models.DateField() end_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True,blank=True, null=True) updated_at = models.DateTimeField(auto_now=True,blank=True, null=True) status = models.ForeignKey(TaskStatus, related_name='Status',on_delete=models.CASCADE) def __str__(self): return(self.name) Please help -
How to switch HTML page in Python with Django
Template : <a class="btn btn-primary" href="{% url 'edit' %}">Edit</a>ù views.py: def edit(request): return render(request, "edit.html") urls.py: urlpatterns = [ path("", views.index, name="index"), path("wiki/create", views.create, name="create"), path("wiki/edit", views.edit, name="edit"), path("wiki/<str:name>", views.entry, name="entry"), path("search", views.search, name="search"), path("save", views.save, name="save"), path("random", views.random, name="random"), ] I would like simply to switch from an HTML page on another, but the function gives me this error: TemplateDoesNotExist at /wiki/edit edit.html But the template exist, I created it. I tryed a lot of changes but all of them gives me error. Thank you. -
Django, append value to a foreing key list
I have set the following model structure: class Prodotto(models.Model): name = models.CharField('Nome del Prodotto', max_length=30) class ProdottoFilter(models.Model): prodotto=models.ForeignKey(Prodotto, on_delete=models.CASCADE, null=True) After that I have created a form using the ProdottoFilter model. Here my views.py: ... if request.method == 'POST': form = ProdottoFilterForm(request.POST) if form.is_valid(): prodotto = form.save() else : form = ProdottoFilterForm() Now I want to appened a value to the variable prodotto, ad example the value "Tutti i prodotti". I have tried: a="Tutti i prodotti" prodotto.insert(0,a) But python give me the following error: 'ProdottoFilter' object has no attribute 'insert' -
how to send audio recorded in client side to backend
i want to record the audio and send it to backend.I used getUsermedia for getting the audio from client side.i Can generate download link, But cant figure out how to send it to backend. I'm using django framework. script.js media = mv.checked ? mediaOptions.video : mediaOptions.audio; navigator.mediaDevices.getUserMedia(media.gUM).then(_stream => { stream = _stream; id('gUMArea').style.display = 'none'; id('btns').style.display = 'inherit'; start.removeAttribute('disabled'); recorder = new MediaRecorder(stream); recorder.ondataavailable = e => { chunks.push(e.data); if(recorder.state == 'inactive') makeLink(); }; log('got media successfully'); }).catch(log); } start.onclick = e => { start.disabled = true; stop.removeAttribute('disabled'); chunks=[]; recorder.start(); } stop.onclick = e => { stop.disabled = true; recorder.stop(); start.removeAttribute('disabled'); sendVideoToAPI() } function makeLink(){ let blob = new Blob(chunks, {type: media.type }) , url = URL.createObjectURL(blob) , li = document.createElement('li') , mt = document.createElement(media.tag) , hf = document.createElement('a') ; mt.controls = true; mt.src = url; hf.href = url; hf.download = `${counter++}${media.ext}`; hf.innerHTML = `donwload ${hf.download}`; li.appendChild(mt); li.appendChild(hf); ul.appendChild(li); } function sendVideoToAPI () { const url = '/upload/' let blob = new Blob(chunks, {type: media.type }); let fd = new FormData(); let file = new File([blob], 'recording'); fd.append('data', file); console.log(fd); let form = new FormData(); let request = new XMLHttpRequest(); form.append("file",file); request.open("POST",url, true); request.send(form); console.log(form) console.log("Sended..") } urls.py urlpatterns = … -
Show most voted member of related model in serializer
I have the following models: Question class Question(models.Model): question_text = models.CharField(max_length=450) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Answer class Answer(models.Model): question = models.ForeignKey(Question, related_name='answers', on_delete=models.CASCADE) answer_text = models.CharField(max_length=5000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) posted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) VoteAnswer class VoteAnswer(models.Model): answer = models.ForeignKey(Answer, related_name='votes', on_delete=models.CASCADE) voted_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Question Serializer class QuestionSeriaizer(serializers.HyperlinkedModelSerializer): answer_count = serializers.SerializerMethodField() posted_by = UserDetailSerializer(read_only=True) class Meta: model = Question fields = ('url', 'id', 'question_text', 'created_at', 'updated_at', 'posted_by', 'answer_count', 'page', 'who_can_answer') depth = 1 @staticmethod def get_answer_count(obj): return obj.answers.all().count() What I want to achieve: There should be a 'top_answer' field in the question serializer which has the answer with the most votes. I have tried the following with no success: class QuestionSeriaizer(serializers.HyperlinkedModelSerializer): answer_count = serializers.SerializerMethodField() top_answer = serializers.SerializerMethodField() posted_by = UserDetailSerializer(read_only=True) class Meta: model = Question fields = ('url', 'id', 'question_text', 'created_at', 'updated_at', 'posted_by', 'answer_count', 'page', 'who_can_answer', 'top_answer') depth = 1 @staticmethod def get_answer_count(obj): return obj.answers.all().count() @staticmethod def get_top_answer(obj): return obj.answers.annotate(total_votes=obj.answers.votes.all().count()).order_by('total_votes').first() -
Dictionary filtering based on key does not works
I have the following dict: ricavi={'Pergolato Recensione Completa': [0, 0, 0, 0, 0, 0, 200.0, 0, 150000.0, 0, 0, 0]} I want to filter for key based on another variable, named prodotto that contains all key filtered. prodotto=['Pergolato Recensione Completa'] How could get it? I have tried the following code but does not work: ricavi= dict((key,value) for key, value in ricavi.items() if key == prodotto) -
How to get a string from HttpResponse or render to a string in Python/Django?
Currently, I have the following code: from django.shortcuts import render # ... def prerender(js: json) -> str: # ... response = render(None, 'partial/name.html', context) return response.content.decode() Is there a way in Django to render to a string rather than to the bytes of HttpResponse? Otherwise, how to get HttpResponse content as a string properly? -
Django passing parameters to url tag according to user input
I have the following href in my template: <a onclick="location.href='{% url 'doctormonthbilling' %}{% urlparams month=monatAMA doctor=arztAMA %}?' "></a> and this url pattern: path('doctormonthbilling/<str:month>/<str:doctorid>', views.doctormonthbilling, name='doctormonthbilling'), Basically monthAMA and arztAMA are 2 dropdown lists where the user chooses a month and a doctor from the list. I want to add the selected values to the url. i was hoping i can "simply" add them like so: {% url 'doctormonthbilling' month=monatAMA & doctor=arztAMA %} but it doesn't work. So i went through some stackoverflow questions and saw a self defined tag. So i implemented it as follows: @register.simple_tag def urlparams(*_, **kwargs): safe_args = {k: v for k, v in kwargs.items() if v is not None} if safe_args: return '?{}'.format(urlencode(safe_args)) return '' and i get the following error: Reverse for 'doctormonthbilling' with no arguments not found. 1 pattern(s) tried: ['doctormonthbilling/(?P[^/]+)/(?P[^/]+)$'] How can i get the values from the selected fields and add them to the url? Thanks!