Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-select2 expose ajax endpoint for external use
im using django select2 for a chained single model select in register webpage. as i know django select2 expose an ajax endpoint that make all that is needed to search, paginate and select my cities. there is a way i can use this service that django-select2 creates automatic for using it in my app? city = forms.ModelChoiceField( queryset=City.objects.all(), label=u"City", widget=ModelSelect2Widget( model=City, search_fields=['name__icontains'], dependent_fields={'country': 'state__country'}, max_results=20, attrs={'class': 'form-control','width': '100%',}, ) ) this is my city widget, and i have a a custom widget that did to test if i can expose it to everyone class TitleSearchFieldMixin(object): search_fields = [ 'name__icontains', 'pk__startswith' ] class CitySelect2TagWidget(TitleSearchFieldMixin, ModelSelect2Widget): model = City def get_queryset(self): return self.model.objects.filter() def label_from_instance(self, obj): return force_text(obj.name).upper() class CountrySelect2TagWidget(TitleSearchFieldMixin, ModelSelect2Widget): model = Country dependent_fields = {'country': 'country'} def get_queryset(self): return self.model.objects.filter() def label_from_instance(self, obj): return force_text(obj.name).upper() thanks a lot for your answers -
Running Keras model on Django
I have trained (using keras) an expression recognition neural network. Now I want to use it as a web service with Django, that detects your expression via webcam live and continuously. I have tried several approaches. First one was to convert my trained model to Tensorflow.js and execute it every 0.1 seconds with javascript on the client side. That was my favourite one, but my convolutional neural network contains some Gaussian Noise layers and Tensorflow doesn't support them. I could remove them but I don't want to be forced to lose accuracy. Second one was to use my keras model in python on the server side sending ajax requests from the client passing the current frame of the webcam's video. But it doesn't seem a good practise to throw requests and responses from the client to the server and viceversa every 0.1 seconds. Third one was to use Brython to be able to execute python code on client side, but it doesn't seem to work well with keras, as it doesn't allow me to import keras or numpy. I don't know if I may be missing an easier solution or if some of the ones described above contain any error. -
Why does Django return Django object is not iterable error?
What am i getting this error for ? models.py class Category(models.Model): name = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.name class SubCategory(models.Model): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) image_url = models.CharField(default=0, max_length=2000) price = models.IntegerField(default=0) views.py def category(request, pk): categories = Category.objects.get(id=pk) subcategories = SubCategory.objects.filter(category=categories) return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories}) urls.py urlpatterns = [ path('', views.index), url(r'^category/(?P<pk>\d+)$', views.category, name='category'), ] base.html {% for category in categories %} {{ category.name }} {% endfor %} -
get_client() got unexpected keyword 'tried' in Django Cache
I am getting an error on cache.set(key, value, time_expire) Here is my code: from django.core.cache import cache cache_key = 'unique keyname' res = cache.get(cache_key) # res data is None res = 'some data' cache.set(cache_key, res, 60 * 60 * 24 * 30) Settings.py # Cache servers CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis-ha-1/' 'IP1,' 'IP2,' 'IP3' '/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis_sentinel.SentinelClient', } } } But on cache.set I am getting get_client() got unexpected keyword 'tried' Code is being running through Celery. Django==1.10.5 django-celery==3.2.2 celery==3.1.25 django-redis==4.7.0 django-redis-sentinel==1.0 What can be issue ? -
Django 2 Images from STATIC_URL is not loading in Css
I'm working on a Django(2.1.7) project in which I need to load some images in css file. Here's what I have so far: From settings.py: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/assets/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'assets'), ] I have a directory in my main project folder named as assets and also have 'django.contrib.staticfiles' in INSTALLED_APPS and then I have mentioned some images in css as: background: url('/assets/images/demo.png') center no-repeat; The image is available in the images folder but not displaying in the template. What can be wrong here? -
Convert Pillow image to Django ImageField
I am trying to convert a Pillow image to Django ImageField. Basically, I: Take an ImageField as input (from a user submitted form) Open it with Pillow Process it (blur it in that case) Pass it back to my Django Form Try to save the Form ⚠️ This is at the last step that I have the error 'Image' object has no attribute '_committed' (which I believe is that Django is unable to save a Pillow image and that it needs to be converted) def upload_media(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data['image'] pil_image = Image.open(image) blurred_image = pil_image.filter(ImageFilter.GaussianBlur(100)) post = Post(image=image, blurred_image=blurred_image) post.save() return redirect('index') -
How to merge the header with main page in Django template where both are getting data from different querysets?
I have a situation where I want to create search in my page. I want to create search without it mixing with the original page as I need to use this same search in more than one page. I created search table in a div in templates folder and named it MySearch.html. Now, I have included that in the main page as {% include 'MySearch.html'%} and it is able to give me the drop down with static text but not with the options that I am filling with query set. In urls.py - url(r'Search', myproj.type4.views.ShowSearch, name='Search'), In ShowSearch() - def ShowSearch(request): countryqueryset = Type4Main.objects.all().values('country').distinct() return render(request,'MySearch.html',{ 'countryqueryset':countryqueryset, }) In MySearch.html - <!DOCTYPE html> <html lang="en"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <head> <meta charset="UTF-8"/> <title> My Search </title> </head> <body> <div id ="mysearch" name="mysearch"> <table id="mysearchtbl" name="mysearchtbl"> <tr> <th> Country </th> </tr> <tr> <td> <select id="country"> <option value="0">Select</option> {% for country in countryqueryset %} <option value="{{country.country}}">{{country.country}}</option> {% endfor %} </select> </td> </tr> </table> </div> </body> </html> I can only see Select as option when it is merging with the main page. What am I doing wrong? -
Django Rest Framework | How to enable custom ViewSet Action in Browsable API?
I have defined a custom action for my viewset: @action(detail=True, methods=['post'], name = 'Change Passsword') def set_password(self, request, pk=None): """Endpoint method to reset password """ user = self.get_object() serializer = serializers.ChangePasswordSerializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong password."]}, status=status.HTTP_400_BAD_REQUEST) # set_password also hashes the password that the user will get self.object.set_password(serializer.data.get("new_password")) self.object.save() return Response("Success.", status=status.HTTP_200_OK) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST But It's not being displayed anywhere in the browsable API. How can solve this? -
Page not found (404) Django 2
I'm confused please help. I got this error whenever I click on the projects title which suppose to trigger ProjectDetailView: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/projects/7/ Raised by: projects.views.UserProjectListView No User matches the given query. Why the error is raised in the UserProjectListView? Here is my Project Model: class Project(models.Model): name = models.CharField(max_length=100) description = models.TextField() date_created = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('project-detail', kwargs={'pk': self.pk}) My View: class ProjectDetailView(DetailView): model = Project context_object_name = 'projects' class ProjectListView(ListView): model = Project context_object_name = 'projects' template_name = 'projects/project_list.html' ordering = ['-date_created'] paginate_by = 2 class UserProjectListView(ListView): model = Project template_name = 'projects/user_project_list.html' context_object_name = 'projects' paginate_by = 2 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Project.objects.filter(author=user).order_by('-date_created') My URL: urlpatterns = [ path('', ProjectListView.as_view(), name='project-home'), path('<str:username>/', UserProjectListView.as_view(), name='user-projects'), path('<int:pk>/', ProjectDetailView.as_view(), name='project-detail'), path('new/', ProjectCreateView.as_view(), name='project-create'), -
Django REST Framework File Uploads not working
In Django REST Framework file uploads, I have one Model which has couple of fields along with a FileField which is an attachment which is optional. class Task(model.Model): attachment = models.FileField(upload_to=default_location, null=True, blank=True) ... some extra fields There is a ModelViewset for this model to implement CRUD functionality. User can create an entry in the model with/without an attachment. class TaskViewSet(viewsets.ModelViewSet): serializer_class = TaskSerializer def get_queryset(self): return Task.objects.all() Serilaizer has an extra BooleanField to decide whether to keep the last attachment or not. This field would be rendered as a checkbox in the front end. class TaskSerializer(serializers.ModelSerializer): keep_previous_attachment = serializers.BooleanField(default=False) class Meta: model = Task fields = ['id','attachment', 'heading'] When user creates the new entry, it works as expected. it stores the attachment to its default location. When user updates the entry with/without attachment, things dont work as expected. When I use PUT method to the update URL of the ModelViewset, 1. When the django server is restarted, first attempt works fine. Previous attachment is overwritten. 2. All the subsequent requests to the URL does not work. It just renames the older file and the renamed file becomes current attachment. 3. If I use PATCH method, i cant access keep_previous_attachment … -
How to pass Django variables in Angular 7 app
In the current project based on Angularjs 1.6.9, I am passing django constant values through the main html page using 'angular.constant' as shown below. <script type="text/javascript"> angular .module("myDashboardApp") .constant('backendData', { staticUrl: "{% static '' %}", user_id: "{{ user_id }}" }); </script> Now I am rewriting the entire app in Angular 7. How can I pass these values so that it is accessible in all the angular7 components? PS. This is my first project in Angular7 so I am not sure how to access Django values in typescript file. Any help is appreciated. Thanks -
Pinax Stripe - Cannot charge a customer that has no active card
I'm trying to setup one-off charges for my Django applications using Pinax-Stripe, but when i'm trying to create the charge I am receiving the error Request req_v8NSWneLebqYMK: Cannot charge a customer that has no active card I've succesfully added my secret + Publishable key in the settings.py and added the path to the webhook path("payments/", include("pinax.stripe.urls")), I've ran ./manage.py init_customers so existing users gets created as a customer. My current test view is looks like this charges.create(amount=decimal.Decimal("5.66"), customer=request.user.customer.stripe_id) which is based on the code I've read in the documentation - https://pinax-stripe.readthedocs.io/en/latest/user-guide/ecommerce/ If it helps in any way, this is what the default django server prints when I try to create a charge - "GET /dashboard/request/ HTTP/1.1" 500 102444 Do I need to somewhere add a default credit card for testing purposes? -
Checking if two 'time ranges' overlap with one another
I have an object saved in db with time range (t1): 11:45-00:15. Now I have another time range from request : (t2) 00:05-00:10. What is most optimal way to find whether this new time range t2 overlaps with an already saved object with time ranges t1. This is the case of midnight, that is where the day is changing. For same day, i'm successfully able to find overlapping time ranges. I don't have a datetime field, rather i have time field only, hence i have to made do with what i already have. -
How to pass variable x by id from template to my view?
How to pass variable x by id from template to my view ? my template Try It <p id="demo" ></p> <p id="demo1"></p> <script> var x = document.getElementById("demo"); var x1 = document.getElementById("demo1"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { x.innerHTML = "Geolocation is not supported by this browser."; } } function showPosition(position) { x.innerHTML = position.coords.latitude x1.innerHTML = position.coords.longitude } </script> my view : def RegisterOrder(request,ln): user = request.user if request.method == 'GET': data = OrderRegister return render(request, 'reg.html', {'formreg': data,'ln':ln}) else: data = OrderRegister(request.POST) if data.is_valid(): table = models.Order() table.table_num_id = data.cleaned_data['table_num'] table.lan=ln table.user_id=user.id table.long_position=request.GET.get['demo'] table.save() -
Django: problems with urlfields validation when overriding form validation
I have some Form with two urlfields, both not required. The form is used to set the value of JSONField in a Model from these two urlfields (for user convenience), everything works fine. If a user enters something except an URL into url1 or url2, django shows validation error at the form "Enter a valid URL". Now I want to make a user to input URL in ANY of these urlfields. I'm overriding clean method for that: class MyForm(forms.ModelForm): url1 = forms.URLField(required=False) url2 = forms.URLField(required=False) def clean(self): cleaned_data = super(MyForm, self).clean() if not cleaned_data['url1'] and not cleaned_data['url2']: raise ValidationError( _("You should enter at least one URL"), code='no_urls' ) return cleaned_data It works, BUT there is a problem: if user enters some "non-URL" data into url1 or url2 and submits the form, Django raises KeyError with Exception Value: 'url1' (or 'url2') instead of showing a validation error at the form What's wrong? Thanks! -
Django models - using two foreign keys values
I'm pretty new in django so my question might be basic but still it would be great if you could help sicne I don't really know how to even look at this problem besides simplest method. I have model like this: class Role(models.Model): id = models.AutoField(primary_key=True) job = models.ForeignKey('Job', on_delete=models.CASCADE) project = models.ForeignKey('Project', on_delete=models.CASCADE) user = models.ForeignKey('users.User', on_delete=models.CASCADE) And now I would like to pull all roles for the given project: current_project = Project.objects.get(slug=slug_name).prefetch_related('roles') and on the template display all roles as rows with job name (from Job model) and user name (from User model) in loop like this: <tr> <td>{{job.name}}</td> <td>{{user.name}}</td> </tr> -
Generating / Hiding messages from middleware in django
I've got a django app that has some middleware (written in the new style) that checks to see if something a user can register for has become 'full' before the user has finished the process to register for it. If it has become full - the middleware kicks off an error message letting the user know that it's become full and links them to their registration so they can change it. The middleware looks like this: def __call__(self, request): # Code to be executed for each request before # the view (and later middleware) are called. # ....extra logic (working without issue).... full_problem_registrations = Registration.objects.filter( id__in=full_problem_registration_ids ) request.full_problem_registrations = full_problem_registrations request.session['registration_now_full'] = False if full_problem_registrations: request.session['registration_now_full'] = True for problem_reg in full_problem_registrations: reg_url = reverse( "camp_registrations:edit_registration", kwargs={ 'person_id': problem_reg.person.id, 'registration_id': problem_reg.id, } ) url_string = '<a href="%s">' % reg_url error_message = format_html( "The %s %s registration for %s %s at %s</a> has become\ full and is no longer available. Please either remove\ or change this registration." % ( url_string, problem_reg.course_detail.course.camp.name, problem_reg.person.first_name, problem_reg.person.last_name, problem_reg.course_detail.location.name, ) ) existing_messages = get_messages(request) if existing_messages: for message in get_messages(request): # check for duplicates if message.message == error_message: pass else: messages.error( request, error_message, ) else: messages.error( … -
Django Show Subcategories by Category Id
I have a problem (I think) with urls and views. So that, I have 3 categories, and each of them has 3 subcategories. I want to open subcategories when clicked on each category. urls.py: urlpatterns = [ path('', views.index), url(r'^category/(?P<pk>\d+)$', views.category, name='category'), ] views.py: def category(request): categories = Category.objects.all() subcategories = SubCategory.objects.all() return render(request, 'category.html', {'categories': categories, 'subcategories': subcategories} base.html: {% for category in categories%} <a class="dropdown-item" href="{% url 'category' pk=category.pk %}">{{ category.name }}</a> {% endfor %} -
Django Getting Data from Template
We have a notification system in place (model extract below) and every time the site needs to notify any user about anything, it creates a notification. Now we want to show that on every site (we use a global template) a counter of the unread messages without changing every view to deliver it to the template. Is there any way to do this right? class Notification(models.Model): n_id = models.AutoField(primary_key=True) n_body = models.CharField(max_length=1000, null=True) n_recipient = models.ForeignKey(User, related_name='Recipient', on_delete=models.CASCADE) n_read_status = models.BooleanField(default=False) Our query would be Notification.objects.filter(n_recipient=request.user, n_read_status=False).count() but we don't want to call it in every view manually. -
django admin list_display SQL joindata
The pages made of existing php are being changed to python and Django. Existing Query Select l.lawyer_idx, lp.lawyer_profile_path, lp.lawyer_profile_name, lc.lawyer_company_name, lc.lawyer_company_address, lc.lawyer_detail_address, l.lawyer_agent from lawyer l left join lawyer_profile lp on l.lawyer_idx = lp.lawyer_idx left join lawyer_company lc on l.lawyer_idx = lc.lawyer_idx order by l.register_date desc; I made each table at models.py models.py class Lawyer(models.Model): lawyer_idx = models.AutoField('ID', primary_key=True) lawyer_agent = models.CharField(max_length=1, blank=True, null=True) class Meta: managed = False db_table = 'lawyer' class LawyerProfile(models.Model): lawyer_idx = models.AutoField('ID', primary_key=True) lawyer_profile_path = models.CharField(max_length=200, blank=True, null=True) lawyer_profile_name = models.CharField(max_length=100, blank=True, null=True) ................. class LawyerCompany(models.Model): lawyer_idx = models.AutoField('ID', primary_key=True) lawyer_company_name = models.CharField(max_length=100) ............... We would like to place the following query into the list_display portion of Django Admin.py Is there any way to show the data that did join in sql? Admin.py from django.contrib import admin from .models import Lawyer, LawyerCompany, LawyerProfile @admin.register(Lawyer) class LawyerAdmin(admin.ModelAdmin): list_per_page = 100 **list_display = ['lawyer_idx', 'lawyer_agent', 'lawyer_profile_path','lawyer_company_name']** list_display_links = ['lawyer_email'] search_fields = ['lawyer_name'] fields = ('lawyer_name', 'lawyer_email', 'lawyer_mobile') -
How to get 10 of the best-seller-selling products in django?
hello i have this model: class Product(models.Model): title = models.CharField(max_length=100, verbose_name=_('title')) count_sold = models.IntegerField(default=0, verbose_name=_('count sold')) def __str__(self): return self.title How to get 10 of the best-seller-selling products based on the number of sales(count_sold) with query ? thanks. -
How to use Django for loop twice on the same data
I'm attempting to use a for loop to iterate over the same data twice in the same Django template. However the second for loop only returns the first object in the database. Basically I have an image of each job in the database on the homepage and when clicked on it should display a more detailed description of that job. All the jobs from the database display fine on the homepage but they all display the description of the first job when clicked on. I think it's something to do with only being able to use an iterator once but I can't figure out what the solution is. model.py from django.db import models class Job(models.Model): title = models.CharField(max_length=50, default="Example Work") image = models.ImageField(upload_to='images/') summary = models.TextField() views.py from django.shortcuts import render from .models import Job def get_index(request): jobs = Job.objects return render(request, 'index.html', {'jobs': jobs}) index.html {% for job in jobs.all %} <div class="col-md-6 col-lg-4"> <a class="portfolio-item d-block mx-auto" href="#portfolio-modal"> <div class="portfolio-item-caption d-flex position-absolute h-100 w-100"> <div class="portfolio-item-caption-content my-auto w-100 text-center text-white"> <i class="fas fa-search-plus fa-3x"></i> </div> </div> <img class="img-fluid" src="{{ job.image.url }}" alt=""> </a> <h3 class="text-center text-secondary">{{ job.title }}</h3> </div> {% endfor %} <!-- Portfolio Modal --> {% for … -
serializer being called multiple times django python
This is code of serializer which is working perfectly fine.. But,serializer is being called multiple times class StatisticLocationSerializer(serializers.one, two): domains = serializers.SerializerMethodField(read_only=True) statistic = serializers.SerializerMethodField(read_only=True) patents = serializers.SerializerMethodField(read_only=True) inventors = serializers.SerializerMethodField(read_only=True) #### METHOD FIELDS #### def setup_eager_loading(queryset): return something class Meta: model = models.LocationModel fields = ( 'domains', 'statistic', 'patents') lookup_field = 'slug' extra_kwargs = { 'url': {'lookup_field': 'slug'} } ##### THIS IS HOW I"M CALLING SERIALIZER CLASS #### serializer_class = StatisticLocationSerializer def get_queryset(self): queryset = self.get_serializer_class().setup_eager_loading(queryset) NOTE: I CHECKED THE FUCTION get_queryset is also being called only Once -
Crispy Forms: FormHelper for split forms / two columns same model
My Template is divided into two columns. I have only one Model but aiming for split a form into two, one part in the first column, another part in the second column. I aim for using FormHelper for Crispy Forms. Available Documentation does not help me solving this. Below is my code. The two FormHelper divide the Model into two parts, first part with fields: ['car_model_make', 'status_is_secondhand'] second part with fields: ['seller', 'buyer'] What I have been looking for is a way to "call" upon a specific {% crispy form %}, such as {% crispy form|product-modelform_1 %} and {% crispy form|product-modelform_2 %} which does not work, and even if it would work, it will later create a problem for the <form id="product-modelform" method="post"> My initial solution was to have one dynamic part and a fixed coded part, however it creates other problems. How can I do? # models.py class Product(models.Models): car_model_make = models.CharField(default='B', max_length=1, blank=True, choices=CAR_TYPE) status_is_secondhand = models.BooleanField(blank=True) seller = models.CharField(max_length=50, blank=True, choices=SELLER_TYPE) buyer = models.CharField(max_length=50, blank=True, choices=BUYER_TYPE) # forms.py class ProductForm(ModelForm): class Meta: model = Product fields = ('__all__') def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-4' self.helper.field_class = 'col-sm-8' … -
Django paginate by embedded model
I'm using a model in Django which have another embedded model (Imagine Pizza with embedded toppings all stored in a single mongoDB collection). Let's say I have a Detail View that shows a single pizza with all the toppings. How can I paginate that view based on toppings? For example, pizza1 has 50 toppings. I want the Detail View to show me pizza1 fields but when getting to toppings, I want to only show for example 10, then let me paginate 5 pages of toppings in the same view. Thank you.