Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django view function is not showing data of print command
i have make a function in django view and its working fine but there are print functions in it and it is not showing in terminal before it is showing perfectly but no data is printing in terminal but function is working fine for example def uplink(request): print("******************") a=5 b=6 c=a+b print(c) this is just a example function is doing the operation and stored the data but not showing print command datai have never faced this issue -
Django i18n, using template inside python string, how to translate
I need to translate some emails in a django app and I was wondering what is the best way to tag for translation something like this: subject_template = ( 'Enlèvement programmé le {{ pickup.pickup_date|date:"l d F"|lower}} {{ pickup.timeslot }} - ' + "{{ pickup.display_id }}" ) This is a part on an email in a pythons script, however template are used inside the string, so I cannot really use gettext isn't it ? Maybe one of you ended up in a similar situation, if you have a solution that would be neat. -
Iterate through a complex dictionary with python
I would like to browse this dictionary especially the lines sub-array my_dict= { "alla": "koko", "messages": [ { "env": "dlo", "detail": "cons" } ], "commandes": [ { "comande_numero": "lkm02", "date": "14/10/2022", "lignes": [ { "product": "mango", "designation": "04 pacquets of mango", "quantite": 14 }, ...... ] } ] } I tried all_product=my_dict['commandes'] for one_ligne in all_product.lignes: // my code but i have an error, So how to browse the rows sub-array located at the dictionary level -
Integration the bank payment system
I am trying to integrate the Bank's payment system on my Django-based website. As it said in documentation, I need to send parameters to their server (and then the new window should appear and the client should fill his card credentials there). Documentation (part 1): Documentation (part 2): Documentation (part 3): I am new in integration such services (payment) and need some help or broad explanation what to do, why do to that, and how. Additionally, I was pretty sure that the following code wouldn't work fine but why. import requests def send_request(): url = 'https://ecomm.pashabank.az:18443/ecomm2/MerchantHandler/?command=v&amount=5&currency=932&client_ip_addr=167.184.1.132&msg_type=SMS' response = requests.post(url) print(response) send_request() causes raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='ecomm.pashabank.az', port=18443): Max retries exceeded with url: /ecomm2/MerchantHandler/?command=v&amount=5&currency=932&client_ip_addr=167.172.184.123&msg_type=SMS (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1123)'))) Overall, I need help of everything happening behind the scenes. Huge thanks in advance guys! Note: I have also received some certifications from bank (I assume to assure the connection safety). But how I use it and when? -
how to append to list below example given and output also?
This is the data: data=[{"id":1,"name":"vikash","roll":39},{"id":2,"name":"kumar","roll":3}] data2=[{"hobby":"football","food":"any"},{"hobby":"basketball","food":"any"}] list1=[] expected Output: list1:[{"name":"vikash","roll":39,"hobby":"football","food":"any"},{"name":"kumar","roll":3,"hobby":"basketball","food":"any"}] Please help me! -
File Browser-File,Media Management
Hi everyone my question is how can I write file browser code or is it writeable im new on Django and I making control panel and how can I add or write to control panel -
Role choice field data ins't saved for UserRegsitrationForm django
The following error message appears after I submit the SignUpform: 'NoneType' object has no attribute '_inc_path' This issue is related to the role choice field of my CustomUser model. The models function perfectly without the role field and all forms are displayed and saved correctly. I suspect my choice field form does not pass/save correctly the input values to the CustomUser model. Any input would be highly appreciated. Models.py: class CustomUser(AbstractUser): display_name = models.CharField(verbose_name=("Display name"), max_length=30, help_text=("Will be shown e.g. when commenting")) ... country = CountryField(blank=True, null=True) ... role = models.CharField(choices = ROLES, max_length = 50, default = "regular_user",) ... class Meta: ordering = ['last_name'] def get_absolute_url(self): return reverse('account_profile') def __str__(self): return f"{self.username}: {self.first_name} {self.last_name}" ``` forms.py: class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label=_("First name")) last_name = forms.CharField(max_length=30, label=_("Last name")) display_name = forms.CharField(max_length=30, label=_("Display name"), help_text=_("Will be shown e.g. when commenting.")) role = forms.ChoiceField(choices = ROLES, label="Role", initial='Regular_user', widget=forms.Select(), required=True) def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.display_name = self.cleaned_data['display_name'] user.role = self.cleaned_data['role'] user.save() users/create.html: {% extends "wagtailusers/users/create.html" %} {% block extra_fields %} ... {% include "wagtailadmin/shared/field_as_li.html" with field=form.role %} ... {% endblock extra_fields %} settings.py: AUTH_USER_MODEL = 'userauth.CustomUser' WAGTAIL_USER_CREATION_FORM ='userauth.forms.WagtailUserCreationForm' WAGTAIL_USER_EDIT_FORM = 'userauth.forms.WagtailUserEditForm' WAGTAIL_USER_CUSTOM_FIELDS = ['display_name',... 'role', … -
django-pytest ModuleNotFoundError
I'm running django==4.0.7 and python==3.10 and django-pytest==0.2.0. When I run my app using the command python manage.py runserver it works fine. But when I run the command pytest I get module not found error. in the settings.py file I've imported the following: from corsheaders.defaults import default_headers so when i run pytest i get the following error. from corsheaders.defaults import default_headers ModuleNotFoundError: No module named 'corsheaders' Whereas it is corsheaders is already installed django-cors-headers==3.13.0. my pytest.ini [pytest] DJANGO_SETTINGS_MODULE = app.settings python_files = tests.py test_*.py *_tests.py What is going wrong? How could I resolve it? -
Django: Filtering items in generic.ListView
I'm creating a game website and i have these models for games: class Game(models.Model): accountant = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='games') title = models.CharField(max_length=50) bank_money = models.IntegerField() player_starting_money = models.IntegerField() golden_card_amount = models.PositiveIntegerField( validators=[ MinValueValidator(100), MaxValueValidator(1000) ] ) now i want every user to see their own games at dashbard: class DashboardView(mixins.LoginRequiredMixin, generic.ListView): template_name = 'games/dashboard.html' model = models.Game how can i do this (show every user their own games, not all games)? -
Displaying in PDF unique values and count of each unique values
I am having a hard time displaying in pdf all unique values of the category and subcategory versus count of each category under the three tight columns which are the severity. Severity has three options (in Bold). The PDF should have four columns: Accident Causation | Accident Causation Sub Category | Damage to Property | Fatal | Non-Fatal Views def fetch_resources(uri, rel): path = os.path.join(uri.replace(settings.STATIC_URL, "")) return path def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result, link_callback=fetch_resources) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None class GenerateInvoice(View): def get(self, request, *args, **kwargs): try: incident_general = IncidentGeneral.objects.filter(user_report__status = 2).distinct('accident_factor') #you can filter using order_id as well except: return HttpResponse("505 Not Found") data = { 'incident_general': incident_general, } pdf = render_to_pdf('pages/generate_report_pdf.html', data) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Accident Causation" #%(data['incident_general.id']) content = "inline; filename='%s'" %(filename) content = "attachment; filename=%s" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") Models class AccidentCausation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) category = models.CharField(max_length=250) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.category class AccidentCausationSub(models.Model): accident_factor = models.ForeignKey(AccidentCausation, on_delete=models.CASCADE) sub_category = models.CharField(max_length=250, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.sub_category class IncidentGeneral(models.Model): … -
Prevent Url Form from clearing out
I am currently working on a Django project and wanted to create a form that includes the invitation link as the initial URL and a field for the maximum usage of that link. However, when I decide that I want to publish this link, the form is cleared, so the user is not able to publish the link afterwards. Any ideas on how to prevent this or is there another way to solve this problem. form in forms.py view in views.py functions in functions.py -
Scheduling libraries in Python [closed]
I have a requirement where I need to schedule a job in Django. I had gone through various libraries but one issue those libraries didn't resolve is multiple runs of job if the same instance of my app is running on multiple pods. Is there a library which resolves this issue or any other way to resolve this issue? Thanks -
Send filtered data using django via email
i want filter the student data by the skills in the vacancy and then send it to the company who posted the requirements in vacancy via email.does anyone have idea about this. ** The Model** class Student(models.Model): name = models.CharField(max_length=50) skills = models.ManyToManyField(Skill) passout = models.ManyToManyField(Passout) email = models.EmailField(max_length=254 ,null = True) resume = models.ImageField(upload_to='media/resume', height_field=None, width_field=None, max_length=None , null=True) create_date = models.DateTimeField('created date',auto_now_add=True) def __str__(self): return self.name class Company(models.Model): comp_name = models.CharField(max_length=50) loc = models.CharField(max_length=50) hr_name = models.CharField(max_length=50) hr_email = models.EmailField(max_length=254) def __str__(self): return self.comp_name class Vacanccy(models.Model): com_name = models.ForeignKey(Company, on_delete=models.CASCADE) skillreq = models.ManyToManyField(Skill) yearofpass = models.ManyToManyField(Passout) title = models.CharField(max_length=255) expiry_date = models.CharField(max_length=50) def __str__(self): return str(self.com_name) -
Paramiko exec_command, can't make code awaits for task to be completed
I am building a django app under docker. In the views I call a task where paramiko makes a ssh connection from a container to another to run a third party app. The problem is that during the call to the other container I zip the 'results' folder and move it to another place. This requires a bit. The code though goes back to the views and looks for the zip file before it appears where it should be. tasks.py @shared_task() def my_task(): command2 = f"""sudo cp /.../ibt1.msh /.../ibt1.msh && \n cd /... && \n sed -i 's/BUBB MASS.*LECT expl TERM/BUBB MASS {chargeMass} LECT expl TERM/g' ./ibt1.epx && \n sed -i 's/XC.*YC/XC {chargeLon} YC/g' ./ibt1.epx && \n sed -i 's/YC.*ZC/YC {chargeLat} ZC/g' ./ibt1.epx && \n sed -i 's/ZC.*R/ZC 0 R/g' ./ibt1.epx && \n sudo cp ./ibt1.epx ../castemData/ibt1.epx && \n pwd && \n ./europlexus ./ibt1.epx && \n sudo cp ./ibt1.msh ./output/ibt1.msh && \n sudo cp ./ibt1.epx ./output/ibt1.epx && \n sudo cp ./ibt1.listing ./output/ibt1.listing && \n until sudo zip -r result.zip ./output/; do sleep 5; done && \n until sudo mv result.zip /europlexusData/result.zip; do sleep 5; done && \n sudo rm -rf ./output """ host2 = "+" port = ++ username = … -
Django threads working differently with manage.py and gunicorn
I am working in a Django project with REST API that needs to work without a database, so the data is saved in a static dict. The app uses two different datasets that provide information about roads. One of the datasets provides some static data (it might be updated, at most once or twice a year), and the other one provides dynamic data (updated every 5 minutes). The dict will contain an element for each road, each element is created when the static dataset is read, and is updated with the dynamic data every 5 minutes when the dynamic dataset is read. Inside the APP, the static data is read by the main thread, and then is updated once a month by a second thread. The dynamic data is read by a third thread every 5 minutes. When a GET request is sent to the REST API, it should return the content of this dict. It works fine when the app is executed through the "manage.py runserver" command. However, after exporting the project to a docker image (that uses gunicorn), when the app is running, the GET request doesn't get the dynamic data on response, but only the static one … -
Django get queryset with column from another model
Hello this is my model related to default AUTH_USER_MODEL by OneToOneField: class Additional(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) vut_id = models.IntegerField() edit_right = models.BooleanField(default = False) add_access_right = models.BooleanField(default = False) and I need to get Queryset of data Additional model with username from model AUTH_USER_MODEL. If used select_related (Additional.objects.select_related('user').all() ) it returned only id of user: { "model": "authentication.additional", "pk": 13, "fields": { "user": 15, "vut_id": 123456, "edit_right": false, "add_access_right": false } } how i want it to looks like: { "model": "authentication.additional", "pk": 13, "fields": { "username": "user1", "vut_id": 123456, "edit_right": false, "add_access_right": false } } -
django next and previous button in detail page
I’m trying to create a next and previous button on a single(detail) page. I don’t understand how to make this happen. These are my codes views.py def playsong(request, id,slug, tag_slug=None): beat= Number_beat.objects.get(created_beats=id) album = Album.objects.get(album_id= id) albu = Album_beats.objects.filter(album_name= id) bea=Beats.objects.all() nextbeat = Number_beat.objects.filter(id__gt = beat.id).order_by(‘id’).first() #.values(‘id’)[:1] lastbeat = Number_beat.objects.filter(id__lt= beat.id).order_by(‘id’).last() tag= None if tag_slug: tag = get_object_or_404(Tag,slug=tag_slug) beat=beat.filter(tags__in=[tag]) context={ 'beat':beat, 'nextbeat':nextbeat, 'lastbeat':lastbeat, 'album':album, 'albu':albu, } return render(request, 'music/playsong.html', context) html {% if lastbeat %} <li class="page-item"> <a class="page-link" href="{% url 'playsong' lastbeat %}?{{ request.GET.urlencode }}" id="pred">{{ lastbeat }}</a> </li> {% else %} <li class="page-item"> <a class="page-link" href="{% url 'index' %}" id="pred">home</a> </li> {% endif %} {% if nextbeat %} <li class="page-item"> <a class="page-link" href="{% url 'playsong' %}?next={{ nextbeat|urlencode }}" id="predj">{{nextbeat}}</a> </li> {% else %} <li class="page-item"> <a class="page-link" href="{% url 'index' %}" id="pred">home</a> </li> {% endif %} please can anyone help on can I do -
Does race condition(lost update or write skew) happen in Django admin?
In Django views, we can use select_for_update() to prevent race condition(lost update or write skew) so race condition doesn't happen in Django views with select_for_update(). But, even though I googled, I couldn't find any information saying "in Django admin, race condition doesn't happen or select_for_update() is used to prevent race condition". So, in Django admin, does race condition happen? If so, are there any ways to prevent race condition in Django admin? If not, is select_for_update() or other way used to prevent race condition in Django admin? and can I see the code for me? -
Why user.has_perm() is always returning false even after adding permission to user object by first instantiating it?
python manage.py shell code and all the outputs >>> user1 = users[2] >>> print(user1.username) esther >>> print(exam_permissions[3]) core | exam | Can view exam >>> print(user1.has_perm(exam_permissions[3])) False >>> user1.user_permissions.add(exam_permissions[3]) >>> print(user1.has_perm(exam_permissions[3])) False >>> -
Why my django4 Static JavaScript is not working?
My html: {% load static %} <!doctype html> <html lang="en"> <head> <!-- Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap-grid.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap-reboot.min.css' %}" /> <link rel="stylesheet" type="text/css" href="{% static 'bootstrap/css/bootstrap.min.css' %}" /> <!-- Own CSS --> <link rel="stylesheet" type="text/css" href="{% static 'news/css/base.css' %}" /> </head> <body> <div class="topnav" id="myTopnav"> <a href="#home" class="active">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> <div class="dropdown"> <button class="dropbtn">Dropdown <i class="fa fa-caret-down"></i> </button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> <a href="#about">About</a> <a href="javascript:void(0);" style="font-size:15px;" class="icon" onclick="myFunction()">&#9776;</a> </div> <div style="padding-left:16px"> <h2>Responsive Topnav with Dropdown</h2> <p>Resize the browser window to see how it works.</p> <p>Hover over the dropdown button to open the dropdown menu.</p> </div> <!--First own js, then other js--> <script type="text/javascript" src="{% static 'news/js/base.js' %}"></script> <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.bundle.min.js' %}"></script> <script type="text/javascript" src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> </body> </html> My dir: blog --news --template --static ----bootstrap ------css ------js ----news ------css --------base.css ------js --------base.js --media Settings and urls: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ STATIC_DIR, ] urlpatterns += staticfiles_urlpatterns() if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) my base.js: function myFunction() { var … -
Dynamic updating & HTMX
I have this form setup This is what I want to happen; when the user selects an "Indoor Manufacturer" it then provides a list of "Indoor Models" that belongs to the "Indoor Manufacturer". The same thing for "Outdoor Manufacturer" & its Corresponding "Outdoor Models" I can get the above to work fine using HTMX using my code below However, the next step is to add to the HTMX the "Indoor/ Outdoor Same" checkbox, which will copy the data from "Indoor Manufacturer" to "Outdoor Manufacturer". I tried implementing the basics of what I know, but it's not quite doing what I want - in that it is copying over the data, but only once on the first load forms from django import forms from.models import Maintenance from . import models from units.models import System, Cooler, Make from installs.models import Install from bootstrap_datepicker_plus import DatePickerInput, DateTimePickerInput from dynamic_forms import DynamicField, DynamicFormMixin class CreateSystem(DynamicFormMixin, forms.ModelForm): def indoor_choices(form): owner = form['indoor_manufacturer'].value() return Cooler.objects.filter(manufacturer=owner, in_out="indoor") def indoor_initial(form): owner = form['indoor_manufacturer'].value() return Cooler.objects.filter(manufacturer=owner, in_out="indoor").first() def outdoor_choices(form): owner = form['outdoor_manufacturer'].value() return Cooler.objects.filter(manufacturer=owner, in_out="outdoor") def outdoor_initial(form): owner = form['outdoor_manufacturer'].value() #print (form['outdoor_manufacturer'].value()) return Cooler.objects.filter(manufacturer=owner, in_out="outdoor").first() def outdoor_manufacturer_choices(form): same_mamanufacturer = (form['manufacturer_boolean'].value()) condition = (form['indoor_manufacturer'].value()) if same_mamanufacturer is False: return Make.objects.all() … -
How to solve django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (8)")?
I am getting the error on Django after using python3 manage.py runserver on my computer. Error: django.db.utils.OperationalError: (2005, "Unknown MySQL server host 'db' (8)") Why is this error happening? -
ProgrammingError at /products/fetch/ relation"api_product" does not exist LINE 1: ...roduct"."price", "api_product"."description" FROM "api_produ
version: '2' services: products_web: build: ./products command: bash -c "python3 ./products/manage.py makemigrations && python3 ./products/manage.py migrate && python3 ./products/manage.py makemigrations api && python3 ./products/manage.py migrate api && python3 ./products/manage.py runserver 0.0.0.0:8001" volumes: - .:/code ports: - 8001:8001 restart: always depends_on: - db links: - db emails_web: build: ./emails command: bash -c "python3 ./emails/manage.py makemigrations && python3 ./emails/manage.py migrate && python3 ./products/manage.py makemigrations api && python3 ./products/manage.py migrate api && python3 ./emails/manage.py runserver 0.0.0.0:8002" volumes: - .:/code ports: - 8002:8002 restart: always depends_on: - db links: - db orders_web: build: ./orders command: bash -c "python3 ./orders/manage.py makemigrations && python3 ./orders/manage.py migrate && python3 ./products/manage.py makemigrations api && python3 ./products/manage.py migrate api && python3 ./orders/manage.py runserver 0.0.0.0:8003" volumes: - .:/code ports: - 8003:8003 restart: always depends_on: - db links: - db db: image: postgres:10.0-alpine restart: always # volumes: # - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=myuser - POSTGRES_PASSWORD=mypass - POSTGRES_DB=db ports: - 5432:5432 nginx: image: nginx:latest build: ./web ports: - "10080:80" - "10443:443" links: - products_web - orders_web - emails_web depends_on: - products_web - orders_web - emails_web migrate has not being done properly in docker -
Showing Field Data On Another View
Thank You, trying to show the created_date field to the front table but i get an error, if i don't filter and use the all() method i am able to populate all the field data, but i would like to populate created_date field of member.I Get KEY ERROR "list_id" class ListListView(ListView): model = HBTYList template_name = "accounts/modals/nomodal/index.html" paginate_by = 3 def get_queryset(self): qs = self.model.objects.all().order_by('-id') p_f = HbtyCustomerListFilter(self.request.GET, queryset=qs) return p_f.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['dc'] = HBTYItem.objects.filter(hbty_cust_id=self.kwargs["list_id"]) #Fix this method to show created_data context['filter'] = HbtyCustomerListFilter(self.request.GET, queryset=self.get_queryset()) return context -
where to store 1TB media-file in Django project?
I have a Linux server and a Django project on it. My website opens files that can have enormous sizes. Like 100-500GB or even 1,2TB. Now I just drag and drop these files to "Staticfiles" folder inside my Django project. I use Filezilla for this. But is it a general practice to store such big files inside the Django file system? Or there is a way to store them somewhere outside? Because I think that there should be some "storage" independent from the Django project where I can store my big files. If you have experience with that It would be great if you share your opinion.