Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access custom Mixin's method from view - DRF
I have custom mixin, which has a method with headers and fields parameter: class CustomMixin: @action(detail=False, methods=['get']) def do-method(self,request,params): //some stuff here also I have view set: class ModulViewSet(ModelViewSet,CustomMixin): //some stuff here I'm interested how to pass 'params' parameter to do-method in ModulViewSet Thanks in advance -
When request can be None in django-filter
In documentation of django-filter in part with ModelChoiceFilter met this: def departments(request): if request is None: return Department.objects.none() company = request.user.company return company.department_set.all() class EmployeeFilter(filters.FilterSet): department = filters.ModelChoiceFilter(queryset=departments) But how request could be None? We always have request. Thats how request/response model work -
How can I make web video capture in Django project
I am working on a Django Web project. I'm trying to embed the youtube video on my website and click button to capture the video image with dragging the part of it. I followed some codes which use 'canvas2html' in javascript, but it failed catching the video image for some reason. This is my goal. see the embed youtube video on our site and stop the video when we want to capture. click 'capture' button below and it activates mouse to drag and take the part of image we want to download. capture that part of image and download in our local directory. How can I solve this challenging situation? -
Django modal not load js
I would like to execute a js function within a Bootstrap modal with a Django filter form. The modal works fine and i can see the form but some js functionality not works, only if i add again the js inside the filter.html. base.html: {% load static %} <!DOCTYPE html> <html lang="es"> <body> <div class="modal fade" id="custom-modal" role="dialog"></div> {% block content %} {% endblock %} <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script> <script src="{% static 'js/functions.js' %}"></script> <body> </html> list.html: {% extends "base.html" %} {% load static %} {% load app_tags %} {% load widget_tweaks %} {% block content %} ... <button type="button" class="btn card_header_button" onclick="return openCustomModal('{% url element_filter %}')" data-toggle="tooltip" data-placement="top" title="Filtrar"> <span class="fas fa-filter custom_icon"></span> </button> ... {% endblock content %} filter.html: {% load static %} {% load app_tags %} {% load widget_tweaks %} <div class="modal-dialog modal-lg"> <!-- Here show the form --> </div> Any idea how to solve this ? Thanks in advance. -
Flask : Development mode vs Production mode (uWSGI)
I wanted to know the benefits of running Flask in production mode using uWSGI versus running it in development mode. What are the benefits you gain by using production mode? Scaling? Utilize all CPU cores? I would really appreciate it if someone could point out the benefits and differences. -
How to filter using get_queryset in Django Rest Framework?
Currently, the API I'm pulling is as such: http://127.0.0.1:8000/api/locs/data/2 and the output is as such: { "id": 2, "date": "2019-01-07", "hour": null, "measurement": null, "location": 6 } What I want is actually filtering by the location value, so from the API url above, I would love to pull all the data that is from location: 2. How can I achieve that? What I have so far: views.py class LocationDataView(viewsets.ModelViewSet): serializer_class = LocationDataSerializer permission_classes = [IsAuthenticated] authentication_classes = [TokenAuthentication] def get_queryset(self): queryset = LocationData.objects.all() pk = self.kwargs['pk'] queryset = queryset.filter(location=pk) def perform_create(self, serializer): serializer.save() and urls.py from django.urls import path, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'locs', views.LocationListView, 'locs') router.register(r'locs/data', views.LocationDataView, 'locs/data') urlpatterns = [ path('', include(router.urls)), path('locs/forecast-data/', views.getForecastData, name='forecast-data'), ] My question is that, how can I access the pk for the location? -
How to set CSS classes of all form inputs in FormView?
class PetAddView(CreateView,LoginRequiredMixin): model = Pet fields = ['name','animal_type','breed','color','age','height','price','city','sex','photo'] template_name = 'pets/pet-add.html' def get_form(self, form_class=None): form = self.get_form_class()(**self.get_form_kwargs()) form.fields['photo'].widget.attrs.update({'onchange':'preview();'}) for field in form.fields: form.fields[field].widget.attrs.update({'class':'form-control'}) return form There's how i deal with this, but I'm looking for more elegant solution. I need to set all input classes as 'form-control'. And would be great to do this in one line. -
How to change folium map in html
I want to use the HTML button or slider to retrieve the values of the Folium map array received from views.py one by one. <div id="maps" style="width:800px;height:800px;"> <div id="map_on" style="width:800px; height:800px; display:inline;" > <div id="map_on_1h" style="width:800px; height:800px; display:inline;" > {{map.0|safe}} </div> <div id="map_on_2h" style="width:800px; height:800px; display:none;" > {{map.1|safe}} </div> <div id="map_on_3h" style="width:800px; height:800px; display:none;" > {{map.2|safe}} </div> <div id="map_on_4h" style="width:800px; height:800px; display:none;" > {{map.3|safe}} </div> <div id="map_on_5h" style="width:800px; height:800px; display:none;" > {{map.4|safe}} </div> <div id="map_on_6h" style="width:800px; height:800px; display:none;" > {{map.5|safe}} </div> <div id="map_on_7h" style="width:800px; height:800px; display:none;" > {{map.6|safe}} </div> <div id="map_on_8h" style="width:800px; height:800px; display:none;" > {{map.7|safe}} </div> <div id="map_on_9h" style="width:800px; height:800px; display:none;" > {{map.8|safe}} </div> </div> map is folium map array This code does not seem appropriate. when i push the button or change slider, i want to change array index <div id="maps" style="width:800px;height:800px;"> <div id="map_on" style="width:800px; height:800px; display:inline;" > <div id="map_on_1h" style="width:800px; height:800px; display:inline;" > {{map.0|safe}} <--map.index--> </div> </div> please help me -
React&Django stack. Deploy on Heroku when Set Debug = False app Show blank page but admin page working
Problem: When i set DEBUG = False and deployed myapp to the heroku. myapp page is not show anything(blank page) but in "https://myappname.heroku/admin" it's working, and if i run on my locallhost (python manage.py runserver)there's no any problem Setting.py: import os from pathlib import Path import django_heroku import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-()1p5aqa_pt&hjn29=k$%t&hjn29=k$t&hjn29=k$' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['https://sbuilt-react-django.herokuapp.com/', 'http://127.0.0.1:8000/'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'rest_framework', 'corsheaders' ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ] STATICFILES_STORAGE = "django.contrib.staticfiles.storage.ManifestStaticFilesStorage" ROOT_URLCONF = 'sbuilt.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ './build', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'sbuilt.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } DATABASES['default'] = dj_database_url.config( default='postgres://fetjtshpanyppx:76cbb8ac254c5a81c5d96e05c7a22c17af991796cdad577e7fc20ad5f957416c@ec2-54-165-178-178.compute-1.amazonaws.com:5432/dfv2autarb32ks') # Password validation # https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators … -
Django blog ProgrammingError/TemplateDoesNotExist error
Am making a django blog at the moment and i get errors with my code when i try to go in to the superuser admin panel and make a post. When i enter the python runserver i get error. I followed along: https://djangocentral.com/building-a-blog-application-with-django/ If i missed any info for you to help me solve it ask and i will provide it asap. The Errors raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) django.template.exceptions.TemplateDoesNotExist: index.html, APP_project4/post_list.html When i login to superuser and try to click Posts i get error: django.db.utils.ProgrammingError: relation "APP_project4_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "APP_project4_post" ^ In the APP folder views.py from django.views import generic from .models import Post class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' urls.py from django.urls import path from . import views urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] Models.py from django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title … -
How can I perform search operation using raw sql query in django SQLITE
I'm trying to search string in the STAT table's detection field like below: query = "select detection_class, stream_id, track_id, detection_time, " \ "frame_id" \ " FROM stats where stream_id = %s "\ "detection_class like %%s%% group by track_id; " with connection.cursor() as cursor: cursor.execute(query,[stream_id, detection_class]) Here, when I give the word or some character which are contained in detection_class, it returns an error message like thisTypeError('not all arguments converted during string formatting')),. and also if I try like detection_class=%s it works properly when gives while word else it returns None. -
Some help, i an just a newbie
enter image description here I watched a video from codecamp but i can't setup those thing, can someone help?? -
How to set model field automatically in CreateView? (Django)
class PetAddView(CreateView): model = Pet fields = ['name','animal_type','breed','color','age','height','price','city','sex','photo'] template_name = 'pets/pet-add.html' There's my create view. My goal is to provide view with functionality to create record in database. Bu I don't need my users to specify slug instead I need to set it automatically from specified "name" value. Can I? -
How to set validation in Django model depending on fields entered?
I have the following class : class Item(models.Model): price = models.FloatField(validators=[MinValueValidator(0)]) discount = models.FloatField() The discount cannot be greater than the price. How can I do that? -
Django {{ form.as_p }} fields have pre filled values
I'm following a tutorial to create a blog website. link On part 4 he creates an "Add post" page which uses Django's {{ form.as_p }} to create a related form, However a field's value is pre-filled with the default value of that model field. I've search alot but I found no solution. How can I remove this value and show a raw field? Is it necessary to loop through the form and create a custom form? Is this a reasonable way to create a form? I heard that it's outdated and it's best models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=255) page_title = models.CharField(max_length=255, default=title) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('detail', args=str(self.id)) views.py from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Post ... class PostCreateView(CreateView): model = Post template_name = "myblog/submit_post.html" fields = ['title', 'page_title', 'body'] submit_post.html {% extends 'myblog/base.html' %} {% block title %} Create a new post {% endblock %} {% block content %} <h1>Create a new post</h1> <br> <br> <form method='POST'> {% csrf_token %} {{ form.as_p }} … -
Unable to order by multiple columns and seeing different responses of the same query on django shell and via ListAPIView
I am writing a simple chatting feature for a booking application where a customer can send messages to an owner and owner can reply to those messages. Also an owner can be a customer as well. I am storing those messages in a table which is created by this model - class CustomerOwnerMessages(BaseModel): message = models.CharField(max_length=255, blank=False, null=False) customer = models.ForeignKey( User, on_delete=models.PROTECT, blank=False, null=False, related_name="message_from_customer", ) owner = models.ForeignKey( User, on_delete=models.PROTECT, blank=False, null=False, related_name="message_to_owner", ) My task is to get the list of customers who has so far exchanged the messages with the logged in owner. Let say the pk of that owner is 1. So first I planned to get the object of User model like this - owner = User.objects.get(pk=1) Then I decided to get all the messages of this user sent or received as an owner from model CustomerOwnerMessages. Please note that I have defined related_name for each foreign key in the same model. messages = owner.message_to_owner.filter() I have the list of all the instances of messages sent by this owner. Now I just want the list of all the unique instances where the combination (owner, customer) isn't repeated. So I decided to order_by the messages … -
Django LDAP - raised SIZELIMIT_EXCEEDED
Django application can connect to the LDAP server flawlessly. While login I'm getting the below error, search_s('DC=xx,DC=yyy,DC=com', 2, " (objectClass=organizationalPerson)") raised SIZELIMIT_EXCEEDED(('msgtype': 100, 'msgid': 2, 'result': 4, 'desc': 'Size limit exceeded', 'ctrls': []}) How to set the SIZELIMIT in LDAP configuration please help me with this issue. My settings.py, # Baseline Configuration AUTH_LDAP_SERVER_URI='Ldap://xyz.server.com' AUTH LDAP CONNECTION OPTIONS = { ldap.OPT_REFERRALS: 0 } LDAP_IGNORE_CERT_ERRORS = True AUTH_LDAP_BIND_DN = 'CN=dev,OU=Accounts,DC=xy,DC=qwerty, DC=com' AUTH_LDAP_BIND_PASSWORD = 'qwerty123' AUTH_LDAP_USER_SEARCH = LDAPSearch( 'DC=xy,DC=qwerty, DC=com', ldap.SCOPE_SUBTREE, "(objectClass=organizationalPerson)", ['cn'] ) LDAP_USER_ATTRIBUTES="cn,sn,givenName,displayName,employeeID,mail" LDAP_BASE_DN = "DC=xy,DC=qwerty, DC=com" LDAP USE SSL= True LDAP_SEARCH_DOMAINS = "au.pbs,branch1,branch?" AUTH_LDAP_GROUP BASE = "OU=Accounts,DC=xy,DC=qwerty, DC=com" AUTH_LDAP_GROUP_FILTER = '(objectClass=posixGroup)' AUTH LDAP GROUP SEARCH = LDAPSearch( AUTHLDAP_GROUP_BASE, ldap.SCOPE_SUBTREE, AUTH LDAP GROUP FILTER ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType (name_attr="cn") AUTH_LDAP _USER_ATTR_MAP = { 'first name': 'givenName', "last name': 'sn', 'email':'email' } -
Testing a Class method with sessions using Mock in Django
I am new to Django testing and I am slowly getting to grips with Client() and RequestFactory based requests, but I am completely stumped as to how to test the following code correctly. (login is required through the OTPRequiredMixin) class EmailVerificationCode(OTPRequiredMixin, FormView): def time_diff(): # A simplification for the purpose of my question return True def check_code(self): try: if self.time_diff(): if str(self.user_code) == str(self.code): user_record = User.objects.get(pk=self.request.user.pk) user_record.is_user_verified = True user_record.save() messages.success(self.request, _('Your email has been verified - thank you' )) return redirect(reverse('account:user_profile')) else: messages.error(self.request, mark_safe(_( 'Sorry, but your code did not match.' ))) return redirect(reverse('account:verify_email_code')) else: messages.info(self.request, mark_safe(_('Sorry, but your code has expired.<br>' ))) return redirect(reverse('account:verify_email')) except (AttributeError, ObjectDoesNotExist): messages.warning(self.request, mark_safe(_('We are very sorry, but something went wrong. 'Please try to login again' ))) return redirect(reverse('two_factor:login')) This is what I have tried so far: I have successfully mocked the "if time_diff()" to return False, together with the ability to test the user_code/code permutations, using something like: self.view = EmailVerificationCode() self.view.time_diff = Mock(return_value=False) self.view.user_code = '0000000000' self.view.code = '0000000000' self.view.check_code() Which is where I have reached the level of my 'incompetence', as I cannot workout how to test: user_record = User.objects.get(pk=self.request.user.pk) This test requires that I mock a session variable … -
Call template tag linebreaksbr Django in views
How can I use the linebreaksbr template tag in views.py? I've tried in the view but the result is the tag is read as a string. i am displaying data from database by using ajax jquery which is called via html id tag. How can i use the linebreaksbr tag template on the data if using ajax jquery? This is my views.py to call the data. data_row = { 'title' : data_list['title'], 'image' : data_list['image'], 'company' : data_list['company'], 'location' : data_list['location'], 'requirement' : linebreaksbr(data_list['requirement']), 'datetime_posted' : 'Posted ' + formatted_date + " by " + jobsite, 'link' : link, 'detailModelId' : 'detailModel-' + str(i), } data.append(data_row) i += 1 but if i add linebreaksbr in this views, the result is like this enter image description here And this is my ajax jquery <script> $(document).ready(function() { var timer = null; refresh(); $('#keywordTitle, #keywordLocation').keydown(setTimer); $('#check_hari_1, #check_hari_3, #check_hari_14, #check_hari_30').change(setTimer); $('#cat_all, #cat_jobstreet, #cat_kalibrr, #cat_glints').change(setTimer); $(document).on('click', 'a.page-link', function(evt) { evt.preventDefault(); $('#page').val($(this).data('page-number')); history.pushState({}, null, $(this).attr('href')); refresh(); }); function setTimer() { clearTimeout(timer); timer = setTimeout(refresh(), 2000); } function refresh() { s = $('#spinner').clone(); s.removeClass('d-none'); s.appendTo('#job_list'); $.ajax({ url: "/home/jobs-search-api/", method: 'POST', data: { 'page': $('#page').val(), 'keywordTitle' : $('#keywordTitle').val(), 'keywordLocation': $('#keywordLocation').val(), 'check_hari_1': $('#check_hari_1').is(':checked'), 'check_hari_3': $('#check_hari_3').is(':checked'), 'check_hari_14': $('#check_hari_14').is(':checked'), 'check_hari_30': $('#check_hari_30').is(':checked'), … -
Send Email with a Fixed IP in Python
I am working on Project which requires me send email from IP of specific region Only. So What I trying to achieve is I am having IP address of different region. Suppose I want to send email in India I will select IP that has Geo Location of India and send/Reply to Email Using Python smtplib. Kindly help on how to achieve this -
how to custom search using post method in django
I am the new in django. My problem is that I want to do search with URL like http://127.1.8000/shop/search/queryask pattern I don't want to use with query with question mark like ?q=abcd Can any body guide me that how to do this in url,view and django template files. Thanx -
Django ManyToMany relationship(Movie and Genre) - adding a movie object to a genre
I am developing a streaming website. When you upload a movie it gets the genres related to that movie from an API. If the genres are not in the Genre table, they are added in the UploadMovie view. When these genres are added to the table, I am adding the Movie those genres are for with on the last line in the code below. Example given: If I upload the movie: Die Hard 1, which has the following genres: Action, Thriller, those genres are added to the DB, if they doesn't exist already. During the creation of each genre, Die Hard is added to the genre relationship with: genre_to_save.movies.add(Movie.objects.last()) - this should put the movie Die Hard under the genres, action and thriller and it indeed does. However when I check the database, I see that Die Hard is also under every other genre that it is NOT, like Fantasy and Science Fiction. Die Hard is movie object(34) I am sure that I have some flaw in my function view UploadMovie, but I dont know where. Thank you in advance. class UploadMovie(View): def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('/accounts/login') else: return render(request, 'core/video_upload.html') def post(self,request,*args,**kwargs): form = … -
django: CourseNote() got an unexpected keyword argument 'user'
i am writing a function to save notes to the database from a form but it keeps throwing this error CourseNote() got an unexpected keyword argument 'user' and i dont seem to know where this error is coming from. view.py def CourseNote(request, course_slug): course = Course.objects.get(slug=course_slug) user = request.user if request.method == "POST": course = Course.objects.get(slug=course_slug) user = request.user note_title = request.POST.get('note_title') note_content = request.POST.get('note_content') # CourseNote.objects.create(user=user, course=course, note_title=note_title, note_content=note_content) new_note = CourseNote(user=user, course=course, note_title=note_title, note_content=note_content) new_note.save() response = 'Saved' return HttpResponse(response) urls.py path('<slug:course_slug>/save-note', views.CourseNote, name="save-note"), models.py class CourseNote(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="note_user") course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) note_title = models.CharField(max_length=200, blank=True, null=True) note_content = models.TextField(blank=True, null=True) date = models.DateTimeField(auto_now_add=True) -
Convert a raw self join sql to Django orm code (no internal foreign key)
I have Article and Tag models, having a many to many relation through another model of ArticleTag. I want to find that for a given tag "Health", how many times it's been simultaneously with other tags on articles. (e.g. on 4 articles with tag "Covid", on 0 articles with tag "Infection" , etc) I can perform a self join on ArticleTag with some Where conditions and Group By clause and get the desired result: SELECT tag.title, COUNT(*) as co_occurrences FROM app_articletag as t0 INNER JOIN app_articletag t1 on (t0.article_id = t1.article_id) INNER JOIN app_tag tag on (tag.id = t1.tag_id) WHERE t0.tag_id = 43 and t1.tag_id != 43 GROUP BY t1.tag_id, tag.title However I want to stay away from raw queries as much as possible and work with Django QuerySet APIs. I've seen other threads about self join, but their model all have a foreign key to itself. Here are my Django models: class Tag(Model): ... class Article(Model): tags = models.ManyToManyField(Tag, through=ArticleTag, through_fields=('article', 'tag')) class ArticleTag(Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE)) article = models.ForeignKey(Article, on_delete=models.CASCADE)) -
Django rest serializer how to use different versions of saved images?
Всем привет! У меня возник вопрос при работе с изображениями. Я переопределил метод save в моделях, для того чтобы сохранять несколько версий изображения. Теперь я хочу в Сериализаторе использовать вторую сохраненную версию изображения, с измененными пропорциями. Подскажите, пожалуйста, как я могу это сделать и возможен ли такой сценарий? models.py def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image) thumbnail_size = (500, 500) img.thumbnail(thumbnail_size) image_name, image_ext = os.path.splitext(self.image.path) custom_path1 = '{}_500{}'.format(image_name, image_ext) img.save(custom_path1, "JPEG", optimize=True, quality=75)