Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query to fetch highest rated x with mimimum x people rated
model.py class Movie(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) vote_count = models.IntegerField() class Watchlist(models.Model): userid = models.IntegerField() movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.IntegerField() query to fetch top rated movie with minimum 5 people rated. -
Creating an admin-only wiki with django-wiki
I'm looking at integrating django-wiki into a Django admin site as a way for superusers to create documentation that only other superusers can access. Looking through the docs for django-wiki, I can't see an obvious way to easily pull it under the permissions model of the Django admin site, as it is understandably a standalone entity. I see there are settings for CAN_READ, CAN_WRITE and so on, but I don't think these are quite what I want. Is there a way that I can change the permissions model for accessing the wiki so that only users with access to the admin site (i.e. superusers) can do so? At the moment, I've updated the middleware to check whether the user should have access: class MyMiddleware(object): def __call__(self, request): response = self.get_response(request) app_name = resolve(request.path).app_name if app_name == 'wiki' and not (request.user.is_authenticated and request.user.is_superuser): return HttpResponse(status=403) return response This seems a bit ham-fisted to me, and I notice there is more to django-wiki than just the wiki app (such as nyt). I don't need the wiki to be part of the admin site, just share the same permissions setup. I would just like to know the most secure and efficient way of … -
How to validate the registered users with login in django?
Here I am using a non custom user model for saving the users registered and their details are stored in user_requirement model now I want to validate before logging in to the dashboard My models.py: class user(models.Model): username=models.CharField(max_length=20) email=models.CharField(max_length=50,unique=True) password=models.CharField(max_length=50,default='0000000') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.username class User_Requirement(models.Model): user=models.ForeignKey(user,on_delete=models.CASCADE) room = models.ForeignKey(room,on_delete=models.CASCADE) goal = models.ManyToManyField(goal) design = models.ManyToManyField(design) furniture = models.ForeignKey(furniture,on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) My forms.py: class UserForm(forms.ModelForm): class Meta: model = user fields = ('username','email','password') def clean_email(self): # Get the email email = self.cleaned_data.get('email') # Check to see if any users already exist with this email as a username. try: match = User.objects.get(email=email) except User.DoesNotExist: # Unable to find a user, this is fine return email raise forms.ValidationError('This email address is already in use.') class UserRequirementForm(forms.ModelForm): class Meta: model = User_Requirement fields=('room','goal','design','furniture') error_messages = { 'room': { 'required': "Please select any of the room in the first step", }, 'goal': { 'required': "Please select any of the goals in the second step", }, 'design': { 'required': "Please select any of the design in the forth step", }, 'furniture': { 'required': "Please select any of the furniture in the third step", }, } … -
Internal server error while running django using uwsgi
I'm trying to run django project using uwsgi: uwsgi.sh uwsgi --socket :8001 --wsgi-file ./mc/wsgi.py wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mc.settings') application = get_wsgi_application() mc.conf(nginx): # the upstream component nginx needs to connect to upstream django { server 127.0.0.1:8001; } server { listen 8000; server_name 100.100.100.5; charset utf-8; location / { uwsgi_pass django; } } Running uwsgi.sh - interal server error on 100.100.100.5:8000. What is wrong in nginx config? -
I want to store its result in json file. how to do it in django?
i have a function which I want to store it in async mode in elasticsearchapi to reuse it. I want to store its result in json file. how to do it in django? -
Error when displaying fetched data into drop-dwon list in dhango
Hi there i have new issue here with my first project, I need to fill out the list with project list as.... photos here have Views cod , HTML with for loop and the error what i got ... so any ideas .. thanks in advance View code HTML page including for loop Error enter image description here -
Django model objects AJAX GET not getting response
I'm trying to get model objects (municipality) that have the same foreign object key (governorate ) on user click. but I'm getting no response, when I append url I get a 404 No Governorate matches the given query... Here are the models in question: class Governorate(models.Model): name=models.CharField(max_length=100) def __str__(self): return self.name class Municipality(models.Model): name=models.CharField(max_length=100) mun_d=models.TextField() gov=models.ForeignKey(Governorate, on_delete=models.PROTECT) def __str__(self): return self.name def get_absolute_url(self): return reverse('forums-home', kwargs={'municipality': self.name}) Django view def municipality_by_gov(request): if request.is_ajax and request.method == 'GET': gov_name = request.GET.get('gov_name', False) gov = get_object_or_404(Governorate, name=gov_name) gov_muns = Municipality.objects.filter(gov=gov) data = serializers.serialize('json', gov_muns) return JsonResponse(data, safe=False) Django URL path('ajax/MunByGov/', municipality_by_gov, name='MunByGov'), Script $('.GovLink').click(function(){ $('#GovModalLabel').text($(this).data('name')); var gov_name=$(this).data('name'); $.ajax( { type:"GET", url: "{% url 'MunByGov' %}", datatype: 'json', data:{ gov_name: gov_name }, success: function( response ) { var response = JSON.parse(response)[0]; document.getElementById("text-container").innerHTML = response.fields.name; }, }) }); -
Django Rest Framework export csv data from models in background
Currently, I am using DRF version '3.9.2'. I was doing some CSV export from models synchronously. Sample of the code blocks explained as below: urls.py from django.urls import path urlpatterns = [ path('api/users-csv-export/', UsersExportAsCSV.as_view()) ] views.py from rest_framework.views import APIView def get_users_data(): queryset = User.objects.only('first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth') fields = ['first_name', 'last_name', 'created_at', 'email', 'gender', 'date_of_birth'] titles = ['First Name', 'Last Name', 'Date Added', 'Email', 'Gender', 'Date of Birth'] file_name = 'users' return queryset, fields, titles, file_name class UsersExportAsCSV(APIView): def get(self, request): users = get_users_data() data = export_to_csv(queryset=users[0], fields=users[1], titles=users[2], file_name=users[3]) return data utils.py def export_to_csv(queryset, fields, titles, file_name): """ will export the model data in the form of csv file :param queryset: queryset that need to be exported as csv :param fields: fields of a model that will be included in csv :param titles: title for each cell of the csv record :param file_name: the exported csv file name :return: """ model = queryset.model response = HttpResponse(content_type='text/csv') # force download response['Content-Disposition'] = 'attachment; filename={}.csv'.format(file_name) # the csv writer writer = csv.writer(response) if fields: headers = fields if titles: titles = titles else: titles = headers else: headers = [] for field in model._meta.fields: headers.append(field.name) titles = headers … -
Validating JSON for a simple view
I have a simple Django web application that I use for logging personal expenses. I've started writing a new view that will create a webhook to receive transactions from my bank Monzo. So every time there's a new transaction on my account Monzo send a JSON with the details to a URL I specify. And my app is to save this transaction. As this is all that's happening, just one webhook, I decided not to use the Django REST framework and just create a view that receives the JSON from the bank and saves the transaction. The bank resends each transaction two times. Once when the transaction first hits the account, and then usually a second time, once the transaction has been settled (fulfilled). So my view will check if the transaction already exists and then either create a new record or update existing one. So far I've only written a few lines of code and confirmed that the JSON is received and can be accessed in the view. My question is regarding validation. What sort of validation should I do to ensure that the JSON doesn't include anything dangerous and is safe for my view to process? Example of … -
How to correctly perform an AJAX request in Django
I have made a form in the template with a csrf tag, the form output as below: <form id="appl_detail13" action="/13/devices/" method="post"> <input type="hidden" name="csrfmiddlewaretoken" value="gTOpBTi6rljV5dKsGE0kuzD1IkghAlzW7GdiBZw6pMMaMUxJSlVev5YqPef6jhjb"> <input name="appl_checkbox" id="5" type="checkbox" class="form-check-input applcheck" value="13"> </form> My view accepts the request and should send JSON. def ApplicationDetail(request, application_id): if request.method == 'POST': device = Device.objects.all().filter(application_id=application_id) data = serializers.serialize('json', device) return HttpResponse(data, content_type='application/json') else: return HttpResponse('no posted') On checkbox click i perform the ajax request, but i don't send the csrf token: $(".applcheck").click(e=>{ $.post(requestUrl, data=> { console.log(data) }) }) So i get the below error: P.S. I know there are a lot of tutorials on this, but many of them are outdated and there are broken links. -
How can we pass dynamic port names in django .env files
I am trying to pass dynamic port names to the .env file variables in django . So that instead of passing port number again and again , I will just pass the variable name to the url.Here is .env code for which i am looking for Xyz_port = 8000 xyz_url = http://192.168.1.39:{Xyz_port} The current code is like that: Xyz_port = 8000 xyz_url = http://192.168.1.39:8000 -
accessor about django tables2
as title I wanna get the email comfirmation status use django tables2 this is my code email_confirmation = tables.Column(accessor="email_confirmations") but the html show <django.contrib.contenttypes.fields.create_generic_related_manager. .GenericRelatedObjectManager object at 0x7f5eb732ba20> can anyone tell me how to solve it thanks and regards -
Query for highest x in Django
I have 2 models class Movie(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) vote_count = models.IntegerField() def __str__(self): return self.title class Watchlist(models.Model): userid = models.IntegerField() movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.IntegerField() def __int__(self): return self.userid what will be query to fetch highest watched movie -
Python manage.py runserver is not working in django for me
enter image description here Please help seeing this above pic -
String Representation of Model for StackedInlineAdmin in Django Admin
Is there any way to change the string representation of the model just for single StackedInlineAdmin? Like currently it shows: for __str__ def __str__(self): """ Return string representation of ApplicationFrom objects. :return: str """ return '{} - {}'.format(str(self.person), dict(FORM_TYPES)[self.form_type]) But I want the last modified date with it as well, just in this inline admin. Like this: For this behavior, I can change the __str__ method of the model to def __str__(self): """ Return string representation of ApplicationFrom objects. :return: str """ return '{} - {} - {}'.format(str(self.person), dict(FORM_TYPES)[self.form_type], get_standard_date_time_format(self.modified_at)) But the old string representation of this model is currently being used in its own admin and other places in codebase well. What is want is that I should be able to update the string representation of the model just for this admin. We can update the string representation of the model for dropdowns in admin using label_from_instance by overriding formfield_for_foreignkey but I can't find a way to update its representation in StackedInlineAdmin. -
Caught LDAPError while authenticating user: UNWILLING_TO_PERFORM
I'm new to LDAP and Django. I'm trying to implement a LDAP authentication onto my Django application but I think I have trouble connecting to the LDAP server. Here's the error code: Caught LDAPError while authenticating josephsim: UNWILLING_TO_PERFORM({'desc': 'Server is unwilling to perform', 'info': 'Unauthenticated binds are not allowed'}) -- Here is my settings.py -- AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) logger = logging.getLogger('django_auth_ldap') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) AUTH_LDAP_SERVER_URI = "ldap://ldap.m*****.com.my:389" AUTH_LDAP_BIND_DN = "cn=ldap_user,ou=PEOPLE, dc=m*****, dc=com, dc=my" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=PEOPLE, dc=m*****, dc=com, dc=my", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } Actually there's this previous CodeIgniter project handover by ex-employees with LDAP authentication already implemented and now I'm trying to re-implement the same authentication system onto my Django app. Here are the files: -- application/config/ldap_auth.php $config['LDAP_SERVER']="ldap.m*****.com.my"; //set this the LDAP server $config['LDAP_PORT']="389"; $config['LDAP_SUFFIX']="o=M*****Net"; -- application/controller/file.php /* Login Authentication Method : LDAP */ private function _ldap_login() { $ldap_server = $this->config->item('LDAP_SERVER'); $ldap_port = $this->config->item('LDAP_PORT'); $ldap_suffix = $this->config->item('LDAP_SUFFIX'); $ds=ldap_connect($ldap_server,$ldap_port); $s=@ldap_search($ds, $ldap_suffix, "uid={$this->input->post('userid')}"); if ($s) //LDAP Server Connected { $result=@ldap_get_entries($ds,$s); if ($result['count'] != 0) { if (@ldap_bind($ds,$result[0]['dn'],$this->input->post("password"))) Any help would appreciated. -
Highest rated movie with mimimum 5 people rated api
I want to fetch id with maximum rated movie with minimum 5 people rated in django. My code : model.py class Movie(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) vote_count = models.IntegerField() class Watchlist(models.Model): userid = models.IntegerField() movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE) rating = models.IntegerField() view.py class Highest(APIView): def get(self, request): result = Watchlist.objects.filter(rating__gte=5) data = [] for res in result: data.append({ "name": res.movie_id.title, "rating": res.rating }) return Response(data) In this code i'm getting rating greater than 5, but I want to get highest rating with minimum 5 people rated. -
Djano Stripe API Integration Error - Could not verify Stripe's SSL certificate
So, testing in development worked accordingly, but moving to production yields the issue described in the title. I have contacted Stripe and they appear to be neglecting the problem. The issue is intermittent, as if I refresh the page a few times, I can cause the error. It appears to be random. I am using Heroku to run a multi-tenant app with Django. Heroku-18 stack. I have a wildcard cert. TLS version is 1.2 OpenSSL version is 1.1.1 Python version 3.6.10 Stripe version 2.41.1 (installed through pip and API version is up-to-date as well) Error Log Jan 13 21:58:36 app/web.1: raise error.APIConnectionError(msg, should_retry=should_retry) Jan 13 21:58:36 app/web.1: stripe.error.APIConnectionError: Could not verify Stripe's SSL certificate. Please make sure that your Jan 13 21:58:36 app/web.1: network is not intercepting certificates. If this problem persists, Jan 13 21:58:36 app/web.1: let us know at support@stripe.com. In addition to these problems, the webhook I have fails from a 301 redirect. Not sure how my site is being redirected, but all instances of my webhook fail trying to connect to my site. Honestly I am so stuck, so let me know if you need additional information to further help me. -
How to show the user details stored in database in django?
Here, I am having a register page in django after registration I want to go to the login form directly and after login I want to show the details present in the database of the user who logged in These are my models for register and the details: class user(models.Model): username=models.CharField(max_length=20) email=models.CharField(max_length=50,unique=True) password=models.CharField(max_length=50,default='0000000') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.username # This is the user_requirement model where all the details selected by the user will be stored in this model class User_Requirement(models.Model): user=models.ForeignKey(user,on_delete=models.CASCADE) room = models.ForeignKey(room,on_delete=models.CASCADE) goal = models.ManyToManyField(goal) design = models.ManyToManyField(design) furniture = models.ForeignKey(furniture,on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) views.py: def user_register(request): if request.method == 'POST': # if there is a post request in the form user_form = UserForm(data=request.POST) #first of all it is a user_form will be posted details present in the user_form user_requirement_form = UserRequirementForm(data=request.POST)# after posting the details of the user_form post the details if user_form.is_valid() and user_requirement_form.is_valid(): # if user_form & user_requirement form is valid user = user_form.save()#if form is valid save user_requirement = user_requirement_form.save(commit=False) # Set user user_requirement.user = user user_requirement.save() user_requirement_form.save_m2m() messages.success(request,('Project saved successfully')) return render(request,'register.html') else: messages.warning(request, 'Please correct the errors above') else: user_form = UserForm() user_requirement_form = … -
Chartjs to display graph with csv
I was getting a weird error while trying to plot a graph with chartjs in my django template. I was following the document for chartjs but the graphs had a error for CORS blocked. Please help me out on how to get the csv or excel locally for my chart? home.html <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <script src="https://cdn.jsdelivr.net/npm/xlsx@0.14.3/dist/xlsx.full.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datasource@0.1.0"></script> <body> <div class="container"> <canvas id="myChart"></canvas> </div> <script> let myChart = document.getElementById('myChart').getContext('2d'); let massPopChart = new Chart(myChart, { type: 'line', plugins: [ChartDataSource], options: { plugins: { datasource: { url: 'sample-dataset.xlsx' } } }, data: { datasets: [{ backgroundColor: 'rgb(19, 82, 150)', borderColor: 'transparent' }, { backgroundColor: 'rgb(196, 230, 255)', borderColor: 'transparent' } ] } }); </script> </body> -
A self learning chat bot which can integrated with any website
I have to create a AI based chat bot which can be integrated with any website (medical or hotel management). Admin of website can create questions to train the bot according to website and then bot will learn by user interaction. I know basics of machine learning. I have created a bot using this tutorial https://data-flair.training/blogs/python-chatbot-project/. I have used NLTK, pickel, tkinter, numpy. I know libraries like pandas, tensorflow, sklearn, tflearn (just beginner). I am training this system by json file. This is working fine. I want to know: How can make it like an empty bot which can integrated with any website. I am experienced in django(if it's required) I have read I can use Websockets. What should I use or where can find study material for this. I just need a starting point. If question needs modification, please comment. Thanks in advance. -
HTTP to HTTPS with health link on HTTP
I am using the following config in settings file in the Django project hosted on Aws Beanstalk. CORS_REPLACE_HTTPS_REFERER = True HOST_SCHEME = "https://" PROXY_PASS = "http://health/" SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_PRELOAD = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True The problem I am facing is an error with health link. -
Django Filtering Query slow on Large row dataset
I have been facing a slow performance for my site on performing filtering over large rows from the following data. Type of data I'm storing in the field is RAW HTTP Response Body in the body field which has large content in it, I have 32k objects for below Project models. class Project(models.Model): body = models.TextField(null=True,blank=True) Performing filtering over body takes few seconds. >>> Project.objects.filter(body__icontains='x').count() ### 5-6 seconds 20472 I use Django paginator for slicing the data for each page. >>> from django.core.paginator import Paginator >>> data = Project.objects.filter(body__icontains='x') >>> p = Paginator(data,10) >>> p.page(1) ### takes 5-6 seconds here again because this function counts the total number of pages based on data.count() <Page 1 of 2048> And then i pass the paginator data to the template which just loop over and shows the body. {% for each_data in data %} {{ each_data.body }} {% endfor %} For every page of paginator it would take 5-6 wait because paginator function performs the count on the total dataset and return the page range. which is the biggest drawback. Using Normal Python Slicing : >>> data = Project.objects.filter(body__icontains='x') >>> for each_data in data[0:10]: ### 0.1 seconds print(each_data.body) As you can see if … -
how can to use custom admin across applications in django?
I am trying to utilize my admin site manager log in to be used in quizgame app to block non-logged users to view the content, however, account app is responsible for logins, password reset, social logins, so on, but I want to use the same login(superuser) across applications in Django to manage sub-applications and block content from sub-applications using @login_required account/models.py from django.db import models from django.db.models.signals import pre_save from django.dispatch import receiver from django.contrib.auth.models import AbstractUser, BaseUserManager from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from uuid import uuid4 # Create your models here. # hashlib.md5(os.urandom(16)).hexdigest() class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): """Create and save a SuperUser with the given email and password.""" extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is … -
How to filter the ManyToMany of a queryset in django
I have two models, questions and their answers, and I want to fetch ALL questions along with a single answer to them, i.e, the answer which has the maximum count of upvoters for that question. How do I fetch this result in a Queryset(I'll be paginating the result so having a queryset will ease the process) class Question(models.Model): question = models.CharField(max_length = 128) asker = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name="asked_questions") requested = models.ManyToManyField(CustomUser, related_name="answer_requests") followers = models.ManyToManyField(CustomUser, related_name="followed_questions") topics = models.ManyToManyField(Topic, related_name="questions") url = models.CharField(max_length = 150) created_at = models.DateTimeField(auto_now_add = True, blank = True) def __str__(self): return self.question class Answer(models.Model): answer = models.TextField() author = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name="written_answers") question = models.ForeignKey(Question, on_delete = models.CASCADE, related_name="answers") upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_answers") created_at = models.DateTimeField(auto_now_add = True, blank = True)