Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a custom filter search bar in django?
I am trying to create a filter search bar that I can customize. For example, here is a view: class StudentListView(FilterView): template_name = "leads/student_list.html" context_object_name = "leads" filterset_class = StudentFilter def get_queryset(self): return Lead.objects.all() and here is my filters.py: class StudentFilter(django_filters.FilterSet): class Meta: model = Lead fields = { 'first_name': ['icontains'], 'email': ['exact'], } Until now, I can only create a filter search bar that can provide a list of instances that match first_name or email(which are fields in the Lead model). However, this does now allow me to do more complicated tasks. Lets say I added time to the filter fields, and I would like to not only filter the Lead model with the time value I submitted, but also other Lead instances that have a time value that is near the one I submitted. Basically, I want something like the def form_valid() used in the views where I can query, calculate, and even alter the values submitted. Moreover, if possible, I would like to create a filter field that is not necessarily an actual field in a model. Then, I would like to use the submitted value to do some calculations as I filter for the list of … -
AJAC SUCCESS FUNCTION NOT WORKING - DJANGO
i am trying to call an ajax function and the ajax function method is fully executing its function but after performing the saveorder function it is not returning the success method call, even error method and complete method is not working ajax code: function mycart(){ if(localStorage.getItem('cart') != null){ console.log("nnot empty") cart = JSON.parse(localStorage.getItem('cart')); cart = JSON.stringify(cart) $.ajax( { type:"POST", url: `/SaveOrder`, dataType: 'json', data:{ mycart:cart, LastName : $("#Lastname").val(), Firstname : $("#Firstname").val(), Email : $("#Email").val(), Address : $("#Address").val(), Country : $("#Country").val(), State : $("#State").val(), Status : $("#Status").val(), 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success : function(response) { console.log(response); return alert("jjj") }, error : function() { return alert("ffff"); }, complete: function() { return alert("Hey: " ); } }) } } code in views.py file def SaveOrder(request): Orders.objects.create(Firstname = request.POST['Firstname'] , Lastname = request.POST['LastName'] , Email = request.POST['Email'] , Address=request.POST['Address'], Country = request.POST['Country'],State = request.POST['State'] , status = "pending" ) maxid = Orders.objects.aggregate(Max('id')) cart = request.POST['mycart'] res = json.loads(cart) for item in res: print(item) print() purchases.objects.create(orders_id = maxid['id__max'] , price = item['total'] , product = item['product'] , qty = item['qty']) return JsonResponse(res , safe=False) -
Restrict Integer value in the django urls
I have following django url, which allows users to register for any one security code from 1 to 6. path('add/<int:security_code>/', security_views.RegisterView.as_view(), name='register_code'), Url should render the template up to 6 security codes such as https://www.example.com/add/1/ #-- It shoould work https://www.example.com/add/2/ #-- It shoould work https://www.example.com/add/3/ #-- It shoould work https://www.example.com/add/4/ #-- It shoould work https://www.example.com/add/5/ #-- It shoould work https://www.example.com/add/6/ #-- It shoould work https://www.example.com/add/7/ #-- It should throw 404 when user types a number greater that 6. What change I would need to do to restrict url for limited codes, it should throw 404 or bad request error if user manually puts a differrent number. I dont want to modify the view as I would need to add Get as well as Post method. from django.views import generic from core import models class RegisterView(generic.edit.CreateView): model = models.SecurityCode fields = ['name', 'code'] Is there any way we can do it without modifying views part -
How to use trained font in Pytesseract?
I have made a font type within Pytesseract to extract data correctly. How do I integrate this font type into my Heroku project? I'm trying to get Heroku to use my font (my .traineddata file). In my Python script, (how) would it be possible to call the local directory for the font.traineddata file to use it as a 'lang' in the pytesseract functions, without having it in the tessdata folder? (As i have to use the Heroku TESSDATA_PREFIX folder, which I think I cannot add the font.traineddata file to). Thanks! -
How to locate user location to map through ip address in python folium?
I am using Django REST Framework. Now I can Access User IP from the request of user using django-ipware. from ipware import get_client_ip def getlocation(request): client_ip, is_routable = get_client_ip(request) It provides me the IP address of the request from where user is accessing. Now I want to find out latitude and longitude of that IP through which I can place the user location on the folium map. map1 = folium.Map(location=[latitude,longitude], zoom_start=12, control_scale=True,prefer_canvas=True) folium.CircleMarker(location = [latitude,longitude],radius = 20, popup= 'Here You Are',fill=True,fill_color="#3186cc",).add_to(map1) folium.Marker([latitude,longitude], popup ='Your Location').add_to(map1) So How can I get The Latitude and Longitude?? -
Connect Nginx and Django containers [host not found in upstream]
I've created 2 containers for both, Django and Nginx. It's working perfectly on my desktop, but when I pull my images from Docker Hub and run, I got this error: /docker-entrypoint.sh: Configuration complete; ready for start up 2021/08/24 15:09:39 [emerg] 1#1: host not found in upstream "scrimmage:8000" in /etc/nginx/conf.d/default.conf:2 nginx: [emerg] host not found in upstream "scrimmage:8000" in /etc/nginx/conf.d/default.conf:2 Here is my docker-compose.yml version: '3.7' services: scrimmage: image: juniorgunner/scrimmage container_name: scrimmage_app build: context: . env_file: - ./.env ports: - "8000:8000" nginx: build: ./nginx image: juniorgunner/scrimmage-nginx container_name: nginx ports: - "80:80" depends_on: - scrimmage volumes: static: My default.conf file upstream django { server my_server:8000; } server { listen 80; location / { proxy_pass http://django; } } Even after I try to add a network and change to "8000:80" the Django ports like this: version: '3.7' services: scrimmage: image: juniorgunner/scrimmage container_name: scrimmage_app build: context: . env_file: - ./.env ports: - "8000:80" networks: - django_network nginx: build: ./nginx image: juniorgunner/scrimmage-nginx container_name: nginx ports: - "80:80" depends_on: - scrimmage networks: - django_network volumes: static: networks: django_network: driver: bridge And change the the default.conf to this: upstream django { server my_server; } server { listen 80; location / { proxy_pass http://django; } } Still not … -
Create Columns Dynamically using Django
I'm trying to create columns in a Postgres database at runtime using django. Here's what I've tried so far from django.core.management.base import BaseCommand from django.db import connection class Command(BaseCommand): def handle(self, *args, **options): sql = "ALTER TABLE myTable ADD COLUMN myColumn VARCHAR(256);" cursor = connection.cursor() cursor.execute(sql) Even though There's no exception raised from this code, I'm still not able to perform the database changes Note: It's a legacy system, that's why I'm using django 1.5 -
Convert Charfield to string in Python
Hello ladies and gentlemen. My question is simple, I would like to be able to save line breaks in a Postgresql database with Python, but when retrieving the saved and printing it in console or sending it as context to a template (I am developing a project in Django), the line breaks are not applied. >>> from apps.prestamos.models import Aprobado >>> model = Aprobado.objects.last() >>> print('First comment \n Second comment') First comment Second comment >>> print(model.notas) First comment \n Second comment >>> print(str(model.notas)) First comment \n Second comment >>> Any help is welcome. Thank you. -
How do you get select option menu depending on selection from other select option menu?
I am trying to make menu list depending on what has selected from previous selected option. For example, if type is selected American and Day is selected on Monday, I want to populate Menu that is served on Monday in American restaurant from the database. How do I make this work? I can get list from db if it is just one select option menu but I want it to change depending on how previous option is selected. menu.html {% block content %} <p>Type: <select id="type"> <option selected disabled="true"> Menu Type </option> <option value="Japanese">Japanese</option> <option value="American">American</option> <option value="Italian">Italian</option> </select> </p> <p>Day: <select id="day"> <option selected disabled="true"> Day </option> <option value="Monday">Monday</option> <option value="Tuesday">Tuesday</option> <option value="Wednesday">Wednesday</option> <option value="Thursday">Thursday</option> <option value="Friday">Friday</option> <option value="Everyday">Everyday</option> </select> </p> <p>Menu: <select id="menu"> <option selected disabled="true"> Menu </option> <option value="{{ results.id }}">{{ results.menu_name }}</option> </select> </p> {% endblock %} view.py def showmenu(request): # results = Menu.objects.filter(type__isnull=False).distinct('type') results = Menu.objects.filter(Q(type="American") & Q(day="Monday")) return render(request, "menu.html", {"list":results}) -
how to pass parameter to url into the template to redirect to a specific category - django
i made a website hotels , there are some hotels , and i make their rooms into different categories , but in the url i want to show something like this /hotel-name/categories or /hotel-name/rooms/booking but i cant do that in some cases , when the admin one of the hotels access categories via the menu it returns Reverse for 'categories' with no arguments not found. 1 pattern(s) tried: ['categories/(?P[^/]+)$'] this is some of my models class Hotel(models.Model): hotel_name = models.CharField(max_length=40,unique=True) def __str__(self): return self.hotel_name class Room(models.Model): hotel = models.ForeignKey(Hotel,on_delete=models.PROTECT) room_no = models.IntegerField() beds = models.IntegerField(default=2) this is my views.py def hotels(request): hotels = Hotel.objects.all() return render(request,'rooms/hotels.html',{'hotels':hotels}) def categories(request,hotel): lists = Room.objects.filter(hotel__hotel_name=hotel).values('hotel__hotel_name','room_type','beds', 'balcon').annotate(total=Count('pk')).order_by('-total') return render(request,'rooms/categories.html',{'lists':lists}) i know i can access to a room's specific category through hotels.html <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-3 pt-3"> {% for i in hotels %} <a href="{% url 'rooms:categories' i.hotel_name %}"><button class="text-pink-500 bg-transparent border border-solid border-pink-500 hover:bg-pink-500 hover:text-white active:bg-pink-600 font-bold uppercase px-8 py-3 rounded outline-none focus:outline-none mr-1 mb-1 ease-linear transition-all duration-150" type="button"> {{i.hotel_name}} </button></a> {% endfor %} but sometimes i want to let the users access to their rooms through the menu main.html <div class="z-50 h-screen overflow-y-scroll w-72 menunon header" id="menu"> <button class="absolute mr-4 text-white … -
how to use django's urlize tag in a modal?
My modal is working fine,and i have used urlize on my html body well as you can see below, The challenge comes when i need to use urlize in a modal, the data for the span tag in the modal is populated in the script,and i cannot apply the urlize tag like before. this is working well <p class="h-3x">{{post.description|urlize|url_target_blank }} </p> the challenge is using urlize tag in the modal because the span tag is populated in the script. modal: <div style="text-align: center;" class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle"></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <img id="thanks" class="d-block w-100" class="img-responsive" src="#"> </div> <div class="modal-footer justify-content-center"> <span id="deb" class="mr-4"></span> <div> <button type="button" class="btn btn-outline-primary btn-rounded btn-md ml-4" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> script: <script language="JavaScript" type="text/javascript"> $('#exampleModalCenter').on('show.bs.modal', function (event) { var img = $(event.relatedTarget).data('img') // Button that triggered the modal var deb = $(event.relatedTarget).data('deb') $("#thanks").attr("src", img); $("#deb").text(deb); }) </script> -
Browser Output of HTML/Django/Python shows nothing of Python code
I am following Mosh course (Python for beginner (6 hrs)). In the Django project, When listing the products from the database with HTML/Python/Django code. The output not showing it correctly. In fact, it shows blank after the h1 tag. View module code. from django.shortcuts import render from products.models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'product': products}) def new_products(request): return HttpResponse('The Following are our new Products') HTML Code. <ul> {% for product in products %} <li>{{ product.name }}</li> {% endfor %} </ul> The output just show heading Products -
Django Nested Serializer - Return Null Field if condition is fullfiled
I have a nested serializes, which content I need to return as Null in case of the parent-serializer field "is_profile_private" (a boolean) is True. I tried using get_queryset in order to filter the User Profile but no progress was made. Tried using SerializerMethordField() and get_profile() but Django complained about UserProfileSerializer type of object not being allowed to be serialized. serializers.py class UserProfileSerializer(UserSerializer): height = serializers.SerializerMethodField() class Meta: model = UserProfile fields = ( "bio", "gender", "custom_gender", "non_binary_list", "birthdate", "avatar", "height", "hometown", "zodiac_sign", "language", ) @staticmethod def get_height(obj): return {"value": obj.height, "unit": obj.height_unit} class SimpleUserSerializer(UserSerializer): profile = UserProfileSerializer(source="user", required=False) class Meta: model = User fields = ( "id", "name", "username", "is_profile_private", "date_joined", "profile", ) views.py class UserProfileAPIView(RetrieveModelMixin, UpdateModelMixin, GenericViewSet): lookup_field = "id" queryset = User.objects.all() serializer_class = SimpleUserSerializer http_method_names = ["get"] @staticmethod def get(request, *args, **kwargs): return User.objects.get(id=str(request.data)) -
Django Server Error integrating Newsletter signup
I am having an issue integrating my mailchimp signup to my Django server. I am using Django as a server, then connecting it to my frontend with react native. When going to this url (http://127.0.0.1:8000/subscribe_email) I get the following error: AssertionError at /subscribe_email 'MailSubscriptionAPIView' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method. What am I doing wrong? I just want to be able to use the post method to subscribe a user. Here's my views.py # Mailchimp Settings MAILCHIMP_API_KEY = settings.MAILCHIMP_API_KEY MAILCHIMP_DATA_CENTER = settings.MAILCHIMP_DATA_CENTER MAILCHIMP_LIST_ID = settings.MAILCHIMP_EMAIL_LIST_ID class MailSubscriptionAPIView(GenericAPIView): def subscribe_email(email): mailchimp = Client() mailchimp.set_config({ "api_key": MAILCHIMP_API_KEY, "server": MAILCHIMP_DATA_CENTER }) member_info = { "email_address": email, "status": "subscribed", } try: mailchimp.lists.add_list_member(MAILCHIMP_LIST_ID, member_info) except ApiClientError as error: print(error.text) def post(self, request, *args, **kwargs): email = request.data['email'] MailSubscriptionAPIView.subscribe_email(email) return Response({ "status_code": status.HTTP_200_OK, "message": "Mail added to mailchimp" }) urls.py urlpatterns = [ path('', include(router.urls)), path('subscribe_email', MailSubscriptionAPIView.as_view(), name= 'subscribe-email' ), ] Any help is appreciated! -
When I enter startapp command in django, app did not be added in project
I'm making website using django by pycharm pro version. A command "python manage.py startapp 'app name'" worked well before, but unexpectedly, the command does not work now. when I enter the command in terminal, in terminal, there is nothing difference. but app doesn't develop in the file, so I retry the command, CommandError: 'app name' conflicts with the name of an existing Python module and cannot be used as an app name. Please try another name. commanderror raised... what is the problem? I want to know the solution. -
How to get your own Pytesseract font in Heroku project?
I have a Vue, Django integrated project. I hosted the Vue project on Netlify and the Django project on Heroku. A python script (integrated into Heroku) is called on certain buttons which extract data and posts this to the Django API to be viewed on the frontend. Now in my normal project I have made a font type within Pytesseract to extract data correctly. How do I integrate this font type into Heroku? I'm trying to get Heroku to use my font (my .traineddata file). So I have it in my local tessdata folder (the traineddata file, in the same directory as the normal 'eng' data file), but don't know how to get it on Heroku. Thanks! -
Django Password Reset Confirm error (custom user model)
I am not that experienced writing Python/Back-end, but trying to improve. In development/localserver I am trying to create a password reset form... but I got the following error when accessing the link from the forgot password email - and before that the password was not saving: get_context_data() missing 1 required positional argument: 'user' forms.py (almost copy/paste from Django's form; minor changes) class ResetPasswordForm(SetPasswordForm): error_messages = { 'password_mismatch': static_textLanguage['page_user_passwordReset_alert_passwordNotMatch'], 'password_empty': static_textLanguage['global_alert_mandatoryField'], 'minimum_length': static_textLanguage['global_alert_minCharacters_password'], } new_password1 = forms.CharField( required=False, widget=forms.PasswordInput(attrs={ 'id': 'page_userPasswordReset_content_form_input_passwordA', 'maxlength': '25', 'class': 'global_component_input_box' }), ) new_password2 = forms.CharField( required = False, widget=forms.PasswordInput(attrs={ 'id': 'page_userPasswordReset_content_form_input_passwordB', 'maxlength': '25', 'class': 'global_component_input_box' }), ) def __init__(self, user, *args, **kwargs): self.user = user super(ResetPasswordForm, self).__init__(user, *args, **kwargs) def clean_new_password1(self): password1 = self.cleaned_data.get('new_password1') if password1 == '' or password1 is None: raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty') elif len(password1) < 8: raise forms.ValidationError(self.error_messages['minimum_length'], code='password_too_short') return password1 def clean_new_password2(self): password1 = self.cleaned_data.get('new_password1') password2 = self.cleaned_data.get('new_password2') if password2 == '' or password2 is None: raise forms.ValidationError(self.error_messages['password_empty'], code='password_field_empty') if password1 and password2: if password1 != password2: raise ValidationError(self.error_messages['password_mismatch'], code='password_mismatch') password_validation.validate_password(password2, self.user) return password2 def save(self, commit=True): password = self.cleaned_data["new_password1"] self.user.set_password(password) if commit: self.user.save() return self.user views.py class UserPasswordResetView(auth_views.PasswordResetConfirmView): template_name = '../frontend/templates/frontend/templates.user/template.page_passwordReset.html' form_class = ResetPasswordForm post_reset_login = True success_url = reverse_lazy('page_userLoginPrivate') def … -
shuffle HTML list element order - django
I want to shuffle list when the user open the page he will see every time different order for example: <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> -
Django 3 - password reset - not generating email
I've followed multiple sources on how to set this up. Now everything seems working (no error) but I just don't see the email. gmail - Allow less secure apps: ON url.py path('pw_reset/', auth_views.PasswordResetView.as_view(template_name="authacc/pw_reset.html"), name="reset_password"), path('pw_done/', auth_views.PasswordResetDoneView.as_view(template_name="authacc/pw_done.html"), name="password_reset_done"), path('pw_confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="authacc/pw_confirm.html"), name="password_reset_confirm"), path('pw_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="authacc/pw_complete.html"), name="password_reset_complete"), settings.py #SMTP Configuration EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') What I've tried... use debuggingserver to check the email locally. settings.py EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 cmd python -m smtpd -n -c DebuggingServer localhost:1025 I can see the "Password reset sent" page, but no email is generated. So I suspect there's something wrong with the default PasswordResetView? Probably similar problem, but unresolved: Reset password emails in Django -
gunicorn prevent HUP after it has been triggered
Based on Gunicorn's documentation there is no hook for pre_worker_exit. What I am basically trying to achieve is to prevent workers from exiting if some criteria are met. In my Django application, I have some functions that due to race condition, they are being initiated after the HUP signal and therefore once the workers exit and new ones are spawned, the functions get interrupted in the old workers. Is there a way to stop the HUP signal after it has been triggered or have some kind of pre_worker_exit hook that will check if some criteria are met and therefore delay the worker exiting? Thanks -
export a table with a foreign key to excel
I have these 2 models: class Canva(models.Model): name = models.CharField(null=True, blank=True, max_length=255) site = models.CharField(null=True, blank=True, max_length=255) def get_absolute_url(self): return reverse('bilans:canva_detail', kwargs={'pk': self.pk}) def __str__(self): return self.name class Bilan(models.Model): agregat = models.CharField(null=True, blank=True, max_length=255) SCF = models.CharField(null=True, blank=True, max_length=255) canva = models.ForeignKey('Canva', null=True, blank=True, on_delete=models.CASCADE, related_name='bilan_canva') I have this page that lists the objects of Canva: {% for c in canva %} <a class="btn btn-info btn-outline-dark w-auto mb-2" href='/canvas/consult/{{c.pk}}'>{{ c.name }}</a> {% endfor %} that link lead to this page that show the objects in Bilan that match canva primarykey: {% for bilan in canva.bilan_canva.all %} <table width="100%" border="1"> <tbody> <tr> <th scope="col">{{ bilan.agregat }}</th> <th scope="col"> {{ bilan.SCF }} </th> </tr> </tbody> </table> {% endfor %} I added this link at the end of the html page to export to excel: href="{% url 'bilans:export_excel' %}" role="button" class="btn btn-secondary w-50">export to excel this is the view.py: def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="Canvas.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('canvas list') # this will make a sheet named Users Data # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['agregat', 'scf', 'mois1', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # … -
How to view other group members if i am a member of that group?
In my mobile app,i am trying to create a system which i can fetch other group members that are already member to groups i belong to.But i can only fetch myself,rather than them.How can i do it? Note: I can fetch them from GroupViewSet that i am in,but i have to access to them in GroupMemberViewSet so if i am admin of that group i can patch the groupmember's membership. Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=40,unique=True,default='undefinedusername') class Group(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50,blank=True) class GroupMember(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='groupmembers') group = models.ForeignKey(Group,on_delete=models.CASCADE,related_name='groupmembers_set') isadmin = models.BooleanField(default=False) ismod = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) Views.py class GroupMemberViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = GroupMember.objects.all().order_by('-timestamp') serializer_class = GroupMemberSerializer filter_backends = [UserFilterBackend] Filters.py class UserFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.filter(author=request.user) -
Adding additional information into each form field
I am using Django/Wagtail and the wagtailstreamforms package to build forms. Unfortunately you cannot add two fields side-by-side in the wagtailstreamforms form builder out of the box, so I am trying to add a functionality that allows the user to input an integer 1 to 12 (based on Bootstrap columns - col-1 to col-12) for each field and this number will be retrieved in the templates and will be used. In the wagtailstreamforms_fields.py file, I've started to override the CharField model to add the extra width integer: from django import forms from wagtailstreamforms.fields import BaseField, register from wagtail.core import blocks class CustomCharField(forms.CharField): def __init__(self,*args, **kwargs): self.width = kwargs.pop('width') super().__init__(*args,**kwargs) @register('singleline') class Column_SingleLineTextField(BaseField): field_class = CustomCharField def get_options(self, block_value): options = super().get_options(block_value) options.update({'width': block_value.get('width')}) return options def get_formfield(self, block_value): options = super().get_formfield(block_value) return options def get_form_block(self): return blocks.StructBlock([ ('label', blocks.CharBlock()), ('help_text', blocks.CharBlock(required=False)), ('required', blocks.BooleanBlock(required=False)), ('default_value', blocks.CharBlock(required=False)), ('width', blocks.IntegerBlock(help_text="Width of field, 1 to 12, 12 is full width.", max_value=12, min_value=1, default=12, required=True)), ], icon=self.icon, label=self.label) This code adds the extra integer input for the singleline field in the wagtailstreamforms form builder page in Wagtail settings. Now the issue I'm facing is, I'm not able to retrieve the width parameter in the templates. … -
Django database does not exists in postgreSQL container?
How can I connect my postgreSQL database container with my django application. I have created the postgreSQL container and with this command docker exec -it ae732 bash I gained the bash and entered into psql and created a database and with this container ID I used this container ID with docker-compose file as shown below. services: app: build: context: . environment: - SECRET_KEY=changeme - ALLOWED_HOSTS=127.0.0.1,localhost depends_on: - db db: image: postgres restart: always volumes: - static_data:/static/db ports: - 5432:5432 environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres container_name: ae73234b58e8 proxy: build: context: ./proxy volumes: - static_data:/vol/static ports: - 80:8080 depends_on: - app volumes: static_data: But still the django application says that database doesn't exit even-though I saw it is in there in postgreSQL container. -
I am trying to learn pytest and 1 test case keep failing with details shared below
#!/usr/bin/python -- coding: utf-8 -- #I have written pytest as per #comments in test_invetory.py file.All test cases are passed but only 1 still failing. can someone please help me with ans. -------Given Files: inventory.py------ class InsufficientException(Exception): pass class MobileInventory: def __init__(self, inventory=None): if inventory is None: self.balance_inventory = {} else: if not isinstance(inventory, dict): raise TypeError('Input inventory must be a dictionary') for model in inventory: if not isinstance(model, str): raise ValueError('Mobile model name must be a string' ) if not isinstance(inventory[model], int) \ or inventory[model] < 0: raise ValueError('No. of mobiles must be a positive integer' ) self.balance_inventory = inventory def add_stock(self, new_stock): if not isinstance(new_stock, dict): raise TypeError('Input stock must be a dictionary') for model in new_stock: if not isinstance(model, str): raise ValueError('Mobile model name must be a string') if not isinstance(new_stock[model], int) \ or new_stock[model] < 0: raise ValueError('No. of mobiles must be a positive integer' ) if model in self.balance_inventory: self.balance_inventory[model] += new_stock[model] else: self.balance_inventory[model] = new_stock[model] def sell_stock(self, requested_stock): if not isinstance(requested_stock, dict): raise TypeError('Requested stock must be a dictionary') for model in requested_stock: if not isinstance(model, str): raise ValueError('Mobile model name must be a string') if not isinstance(requested_stock[model], int) \ or requested_stock[model] < 0: raise …