Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get url and pass it as a url parameter in django
i want to pass url as a url parameter for example in my website there are two hotels (hotel A and hotel B) in home page it only shows two buttons one for access hotel A and the other for hotel B i want to get the first url and pass it as url parameter for example my-ip/hote-A get the hotel-A in the url and pass it as url parameter class Hotels(models.Model): hotel_name = models.CharField(max_length=40,unique=True) def __str__(self): return self.hotel_name def hotels(request): hotel_lists= Restaurants.objects.all() return render(request,'hotel/lists.html',{'lists':hotel_lists}) <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 lists %} <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 %} </div> till here everything works fine , but when we select for example hotel A it will bring us to a dashboard which everything should be related with hotel A in my main.html there is a menu which all links should bring us to that data which relates with that hotel class Rooms(models.Model): hotel= models.ForeignKey(Restaurants,on_delete=models.PROTECT) room_number = models.IntegerField() beds = models.IntegerField(default=2) @login_required def categories(request,hotel): lists = Room.objects.filter(hotel__hotel_name=hotel).values('hotel__hotel_name', 'beds', … -
How long does Django's password reset link work?
I just want to know after how much time does the link expire. How long does Django's password reset link work? -
Django: Can I have access to client cookies on first page load?
I need to read a cookie set by Google in order to render my homepage view. But I noticed that, on first load, the object request.COOKIES is always empty. I'm not sure if this is normal, my logic says "when you have a new visitor, all cookies are empty by default, so this is normal", but then, how do tools like Google Optimize work? Is there any way to wait for all client cookies to be set before rendering a view in Django? or will this never be something you'll want to do? I'm having a rough time trying to make an A/B to test work, but I'm starting to think that my approach of reading the cookies on first load was destined to never work. Can someone give me some piece of advice here? -
How to input data in django forms as a list?
I need to forrward this data as python list to django, not as string. How to create list, just to input data separated with commas? class CreateForm(forms.Form): list = forms.CharField(label='Input names (separate with commas): ') -
Django :Uncaught ReferenceError: require is not defined. Is it a django or javascript problem? how i can fix it?
how can use requier function in javascript enter the templates (Django)? -
Marshmallow: How to build a Schema from a nested JSON that includes lists?
I have the following JSON from a payload: { "lunch":{ "appetizer":[ { "size_id":2, "menu_id":34 }, { "size_id":6, "menu_id":78 } ], "entree":{ "start":12, "end":34 }, "dessert":12 } } I need to build a schema subclass using marshmallow.Schema. The lunch will always have an appetizer, entree and dessert keys. The appetizer will be a list of apps, the entree will always have a start and an end, and the dessert will always have a single number. -
Django list view repeatedly fails, but detail pages work
testt1 is my view for taking a queryset and turning out a list of objects and their foreign key children. mydetail is the detail view for the individual objects. No slug is used in the list, but it is in the list template to call the detail pages. But all these errors come from trying to call the list, not the detail. If I just type the slug into the address bar, all my detail pages come up just fine! I have tried a lot of different things, and get a lot of different errors, but the bottom line is always the same: no list named url fails Error during template rendering In template /home/malikarumi/Projects/hattie/templates/base.html, error at line 44 Reverse for 'jhp_url' not found. 'jhp_url' is not a valid view function or pattern name. ‘jhp_url’ is the named url for the detail page. But here is line 44: <link href="{% static 'plugins/owl-carousel/owl.carousel.css' %}" rel="stylesheet"> the urlpattern: path('<slug:slug>/', mydetail, name='jhp_url'), the call to reverse(): def get_absolute_url(self): return reverse(‘jhp_url', kwargs={'slug': self.slug}) namespaced url fails Error during template rendering In template /home/malikarumi/Projects/hattie/templates/base.html, error at line 44 Reverse for 'jhp_url' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['(?P[^/]+)/courts/(?P[-a-zA-Z0-9_]+)/$'] Now it has … -
how to build a url on django outside a template
I have an application that when the user instance is created a signal is dispatched to send an email. I am implementing a signal to send an SMS. On my email HTML template I have this line that redirect the user, I need to send the same link on the SMS. <a href="{{ uri }}{% url 'password-reset-and-active-account' uidb64=uid token=token %}">Aqui</a> the parameters used there is passed through this context context = { 'user': user, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode("utf-8"), 'token': default_token_generator.make_token(user), 'uri': settings.ABSOLUTE_URI } how can I build this URL outside Django Templates, because the {% url 'password-reset-and-active-account' %} will not work outside the template right? -
How do I get List of values from django form template to form.py Cleaned_data
I am actually try to post a list of values ['good','nice','happy'] to the backend. I have following files in my django app. models.py class TagModel(models.Model): name = models.CharField(max_length=255) class BlogModel(models.Model): title = models.CharField(max_length=255) tags = models.ManyToManyField(TagModel) forms.py class BlogForm(forms.ModelForm): title = forms.CharField(widget=forms.TextInput(attrs={ 'placeholder':_('Enter Blog Title'), 'class' : 'form-control border-success' })) blog_tags = forms.ChoiceField(widget=forms.TextInput(attrs={ "name":"blog_tags" })) def clean_title(self): title = self.cleaned_data.get('title') print(title) return title def clean_blog_tags(self): //this line does not get whole list of data tags = self.cleaned_data.get('blog_tags') print(tags) // problem is here return tags class Meta: model = PostModel fields = ['title','blog_tags'] views.py class create_blog(CreateView): template_name = 'blogbackend/create_blog.html' form_class=BlogForm def get_form_kwargs(self): kwargs = super(create_blog,self).get_form_kwargs() print(kwargs) return kwargs Html Template What happen on template is :- I render the title field on the view I added a JS code on Input box , which gets value a create a hidden input with name blog_tags which is same as the filed name in forms.py file After user submit the form I successfully receives the both input values title and blog_tags in my views.py file and successfully display on console with helper function get_form_kwargs() Data is look like this {'initial': {}, 'prefix': None, 'data': <QueryDict: {'csrfmiddlewaretoken': ['4Cm5mvGFv4skPJNTzRI8fKZKq9i7edQbwNmOgCPbDTtu8JQHqE5cd9rQLA8Kzhpu'],'title': ['first'],'blog_tags' : ['good','nice','happy']}>, 'instance':None} Problem When … -
NoReverseMatch at login with Django password reset
I have a small Django application. I am setting up authentication and I have just finished the forgotten/reset password functionality. However, once the password is reset it does not redirect to the success page. I've trawled through all my code and cannot find any references to 'login' that is incorrectly coded. The error that appears is the following: 'Reverse for 'login' not found. 'login' is not a valid view function or pattern name' Here's the relevant files from my project: account urls.py from django.urls import path, include, reverse_lazy from django.contrib.auth import views as auth_views from . import views app_name = 'account' urlpatterns = [ #Login URLs path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), #User Pages URLs path('dashboard/', views.dashboard, name='dashboard'), path('nodes/', include('nodes.urls')), #Password Changes URLs path('password_change/', auth_views.PasswordChangeView.as_view(success_url=reverse_lazy('account:password_change_done')), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), #Password Reset URLs path('password_reset/', auth_views.PasswordResetView.as_view(success_url=reverse_lazy('account:password_reset_done')), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(success_url=reverse_lazy('account:password_reset_complete')), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] password_reset_confirm.html: {% block content %} <div class="page-title"> <h1>Reset Password</h1> </div> <br> <div class="login-container"> <div class="login-box"> <br> <h3 style="text-align: center;">Reset your password</h3> <div class="login-form" style="text-align: center; "> {% if validlink %} <p>Please enter your new password twice:</p> <form method="post"> {{ form.as_p }} {% csrf_token %} <p><input type="submit" value="Change my password"/></p> </form> {% else %} <p>The password … -
django __init__() takes 1 positional argument but 6 were given
My model class: class Campaign(models.Model): name = models.CharField(max_length=255) campaign_id = models.CharField(max_length=8, null=False, blank=False, unique=True) def __init__(self): super(Campaign, self).__init__(self) self.campaign_id = generate_random_id(8) # it generates just random string class Meta: ordering = ["name"] def __str__(self): return self.name My view class: def campaign_list(request): campaigns = Campaign.objects.order_by('name').all() return render(request, 'mp/campaign/list.html', {'campaigns': campaigns}) I got error init() takes 1 positional argument but 6 were given Before creating init in my model everything were working fine. But i assume that now Campaing.object.all() is using constructor and not str. How can i omit this and in .all still use just reffering to name, not creating an object again? -
django: returning django form as response for ajax request
I'm new in django. Now I'm looking for a way to get django form as ajax response. I have prepared an ajax request in my myjs.js file Ajax is sending request by url: 'formJson/<str:skl>/' and my formJson view is getting variable skl and it is used as a key to choose a proper form in forms dictionary included in this view. How can I return this form and use it as response in my ajax success function? Any Idea? myjs.js const skladnikBox= document.getElementById('wybieraj'); const modalTytul=document.getElementById("exampleModalLabel") skladnikBox.addEventListener( 'change', e=>{console.log( event.target.value ); const skl=event.target.selectedOptions[0].text; console.log(skl); modalTytul.innerText=event.target.selectedOptions[0].text; `` $("#exampleModal").modal('show'); ////////////////ajax/////////////////////////////// $.ajax({ type: 'GET', url: `formJson/${ skl }/`, success : function(response){ console.log('success', response); // // const skladnikForm = response.data }, error : function (response){ console.log('error', error)} }) /////////////////////ajax///////////////// skladnikBox.selectedIndex = 0; }) views.py def formJson (request,skl): forms={'witamina A':VitAForm,'witamina E':VitEForm,'Hydrokortyzon': HydrokortyzonForm} form=forms[skl] context={ 'form':form} return JsonResponse(context) urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.home,name='home'), path('formJson/<str:skl>/', views.formJson, name='formJson') ] -
Django dynamic url in root domain overwrites all other urls
I want to have a dynamic root url for different users. All users get their own url. I want to have the dynamic url in the root but also be able to have more hardcoded urls as alternatives, for example on the url that the user will edit their profile. The problem i have is that all urls redirect to view2 and none goes to view1. path(r'edit/<str:user>/', views.view1, name='view1'), path(r'<str:user>/', views.view2, name='view2'), example.com/edit/user always gets redirected to example.com/user which is not wanted. -
Change signup field error message and field color
we are currently implementing a membership page. I hope the color of the field will be red if there is an error, but I don't know what to do. What should I add to my code so that it's possible? <form method="post" class="post-form"> {% csrf_token %} {% for field in form %} <div class="form-group"> <input name="{{field.html_name }}" id="{{ field.id_for_lable }}" class="form-control" type="{{ field.field.widget.input_type }}" value="{{ field.value|default_if_none:'' }}" placeholder="{{field.label}}"> {% for error in field.errors %} <label class="control-label" for="{{ field.id_for_lable }}" style="color: #c13b2a;"><b>{{ error }}</b></label> {% endfor %} </div> {% endfor %} </div> <div class="bbb" style="text-align: center"> <button type="submit">가입하기</button><br> </div> -
How does django handle remote api that either take forever or timeout?
In building a django front-end interface for retrieving data from another remote API and returning it to our user, I'm finding that the remote API often takes over 30 seconds to return a result, and on some occasions it will timeout... even if I wait for an absurdly long 5 minutes. My question is: what is django able to do during this time? Is it blocking execution and therefore reducing the number of connections that it can accept? I'm trying to understand how this works so I can plan my next step - either working with an asynchronous library or rifling off everything to some queue and then using django to check status on that. The app is running in a docker container running gunicorn and nginx. -
BasicAuthentication does not authenticate user when checking permissions
I want to use DRF's rest_framework.authentication.BasicAuthentication to develop my SPA with a dev server while consuming data from a locally running backend. I included rest_framework.authentication.BasicAuthentication in settings.py. I have a view which requires Permission (guardian.mixins.PermissionRequiredMixin): class WidgetDetail(PermissionRequiredMixin, RetrieveAPIView): serializer_class = WidgetSerializer permission_required = "widget.view_widget" return_403 = True If I try to GET the widget using basic auth, the view returns an error 403. Using the debugger, I can see that when PermissionRequiredMixin.check_permissions() is run, request.user is AnonymousUser rather than the user provided by basic auth as DRF's documentation indicates. Why is the user provided by basic auth not identified when permissions are checked? -
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})