Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use an existing table for user login in Django?
Since the tables already exist in the DB for login, I cant use the built-in Django models. I have used inspectdb to map the tables to the project which s working fine, but with login how do I use the existing user model for authentication the views part. This is the User table: class Credential(models.Model): username = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) type = models.ForeignKey('Usertype', models.DO_NOTHING, db_column='type') class Meta: managed = False db_table = 'tb_credential' verbose_name_plural = "Credentials" def __str__(self): return self.username views.py def login(request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') -
Django responds w/ byte literal when DEBUG is True
I'm in the middle of migrating a Django project to Python 3 and updating several dependencies along the way. Right now, I'm using Django 2.2.3. After putting the code on the staging server I noticed that all responses are returned as bytestring literals: b'<html>\n...' This was very hard to narrow down because I first noticed it only on the staging server. Luckily I found out that this has nothing to do with NGINX nor Gunicorn but that DEBUG=True is actually the culrit. The question is: what does DEBUG=True trigger that is messing up the response? -
Django Rest Framework additional authentication checks
I'm developing an app using Django Rest Framework. How can I extend authentication checks on user login? For example, I need to check the is_active and created_at properties of the user that logs in, and allow or disallow the login based on their values, but only after the password was verified by Django. I know about Django and Django Rest Framework custom authentication. https://docs.djangoproject.com/en/2.2/topics/auth/customizing/ https://www.django-rest-framework.org/api-guide/authentication/#custom-authentication The problem is, that requires me to re-implement the built-in authentication checks. I would like to just add checks on top of that. Thanks! -
Django not uploading properly to S3 when running on heroku
I am trying to upload an Image Field using S3, in my local environment it works really well so I am confused on why, when its on heroku, it reads the URL as a double string plus a s3%, makes no sense I have already tried changing STATICFILES_STORAGE and DEFAULT_FILE_STORAGE around, even named it the same thing, but then only generates more errors, I am confused on why this does not function. class Vehicle(models.Model): vehicle_type = models.CharField(max_length=255) vehicle_id = models.CharField(max_length=255) image_url = models.ImageField(upload_to="img/", blank=True, null=True) checked = models.BooleanField(default=False) nfmc_step = models.ManyToManyField(TM, related_name='step') AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_S3_FILE_OVERWRITE = True AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_LOCATION = 'static' MEDIAFILES_LOCATION = 'media' Expected result as in my local machine: https://project-name.s3.amazonaws.com/static/1.jpg What I get: https://project-name.s3.amazonaws.com/static/https%3A/project-name.s3.amazonaws.com/static/img/2_aeS9ZS2.jpg -
How to develop a hybrid system using django for web development and andriod studio as my mobile application?
I'm using python and django framework for web development. I just wanted to know how can I make a hybrid development. I already developed a web that has a admin user, staff user and user. I just wanted to know how I can apply that in mobile and still have the functionality as web. Example, you send a message to your friend on messenger through laptop and your friend receives it on his phone. -
Django media upload not working when uploading image through code
I have created a Django application in which i have a signup page which asks a user to upload their profile picture. When I'm uploading the profile picture through the Django admin panel, the images are being uploaded to the correct path and are being displayed in the website. However, the error comes when I directly select the image to upload when signing up and then When I click on the uploaded image in Django admin it shows page not found and the path to the image is being showed as C:\Users\hp\Workspace\findem\media\image.jpg Settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'findem/static') ] # media folder settings MEDIA_ROOT = os.path.join(BASE_DIR , 'media').replace('\\', '/') MEDIA_URL = '/media/' User Model class UserProfile(AbstractBaseUser, PermissionsMixin): """Represents a user profile inside our system""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255, default=profile_pic) profile_picture = models.ImageField(upload_to='photos/profile_pictures/', default='photos/User.jpg') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) highest_degree_earned = models.CharField(max_length=255, blank=False) college_name = models.CharField(max_length=255, blank=False) graduation_year = models.IntegerField(default=2020, blank=False) Template : <form class="needs-validation" novalidate autocomplete="off" action="{% url 'signup' %}", method="POST" > {% csrf_token %} <div id="Personal_Information"> <h5 class="loginSignup">Personal Information</h5> <div class="form-group row"> <label for="inputprofile" class="col-sm-2 col-form-label">Profile Picture</label> <div class="col-sm-5"> <div class="input-group"> <div class="custom-file"> <input type="file" accept="image/png, image/jpeg, image/gif" … -
How to make integer field fixed to ten numbers output in models
I want user to input their phone numbers with 10 digits, how to set integer field "phone_no" in order to achieve it ? I have set it to default but I want to check number input : models.py class Documents(models.Model): docs_name = models.CharField(max_length=200,verbose_name="Names in Documents") item_type = models.CharField(default="", max_length=100, help_text='*Enter the item name you found e.g. Marksheet,key,wallet',verbose_name="Item type" ) police_station = models.CharField(max_length=255, help_text='*Enter the police station you sending the docs', verbose_name="Police station") phone_no = models.IntegerField(default=0, verbose_name="Phone number") date = models.DateTimeField(default=timezone.now,verbose_name="Date") Description = models.TextField(blank=True, null=True, help_text='*Enter full description about item',verbose_name="Description") pay_no = models.IntegerField(default=0,verbose_name="payment number") publish = models.BooleanField(default=False) image = models.ImageField(default="add Item image", upload_to="DocsImage",blank=False, verbose_name="Images") """docstring for Documents""" def __str__(self): return self.docs_name -
sampleBot matching query does not exist
I'm new in django,I have some codes in my views.py but when I runserver I get the bellow ERROR "sampleBot matching query does not exist" models.py from django.db import models def sample_image_path(instance,filename): return instance.title class sampleBot(models.Model): title = models.CharField(null=True,max_length = 100) sample_image = models.ImageField( upload_to='sample_image_path',null=True) description = models.TextField(null=True) telegram_link = models.CharField(null=True,max_length=50) def __str__(self): return str(self.title) views.py from django.shortcuts import render from app_base.models import sampleBot def sample_details(request,id): ctx ={} ctx ['sample-detail'] = sampleBot.objects.get(id=id) return render(request,'sample-details.html',ctx) urls.py from django.contrib import admin from django.urls import path,include from app_base import views urlpatterns = [ path('',views.home), path('sample-detail/<int:id>',views.sample_details), ] I don't know how can I solve this ERROR. -
How to access subdomain in for ssh tunneling for django multi-tanant app?
One of my friends has a Multi-Tenant Django app running at gitlab ci. He's accessing the app by ssh tunneling and has given it to an android app developer who can access API via IP address. As a multi-tenant app every time a user is created a new subdomain is created. Suppose I created a user named usa. So, this can be accessed by usa.domainname.com. Since we are providing the app developer an ip address. He can access the site but not the subdomains that are created dynamically. Let's say, we have given him the ip 172.168.0.1. He can access the main site with this IP but he cannot access usa.172.168.0.1. When I ran the app I could access it at 'localhost:8000' and the subdomain at 'usa.loclhost:8000'. But I cannot access it at 'usa.127.0.0.1:8000' I understand that we cannot use subdomains with IP address. Because subdomains itself has it's own DNS. I want the app developer to access those dynamically created subdomains via IP. Since it's not deployed anywhere all I have to give the app developer is IP addresses. How can I do that? Thank you. -
how to get backward relation for a set of objects in django?
I have a model for City and Province: class Province(Model): name = CharField(...) class City(Model): name = CharField(...) province = ForeignKey(Province,......, related_name='cities') suppose I have populated the database as below: ontario = Province.objects.create(name='Ontario') quebec = Province.objects.create(name='Quebec') alberta = Province.objects.create(name='alberta') toronto = City.objects.create(province=Ontario, name='Toronto') waterloo = City.objects.create(province=ontario, name='Waterloo') montreal = City.objects.create(province=quebec, name='Montreal) calgary = City.objects.create(province=calgary, name='calgary') I can retrieve a queryset for all of the cities of ontario as below: ontario.cities.all() There are two objects in the above queryset: toronto and waterloo How can I have a queryset of all cities of ontario and quebec? I need a queryset that retrieves toronto, waterloo, and montreal -
How to add information in a page without refreshing the page?
I would like to have a page in my django aplication that has a button that search a product and after selecting quantities gets added to the page (without reloading) in a list where the total get calculated (something like that), I am a beginner in programing and I have a week reading and investigated how to do it but I don't found anything. Is because you need other programming lenguaje? Or could you indicate me some documentation or some example that I can read. Mostly because for my inexperience I don't know how to identify the relevant information in the documentation or even what to look for. -
Django activity user feed is empty
I am trying to implement a Django activity user feed for the currently logged in user in the admin. I created an action with the following code in my view: action.send(request.user, verb="created comment", action_object=comment_object) I have confirmed this creates a corresponding database entry. However, when I access the url - http://localhost:8000/activity/feed/json/, I get an empty response. Can someone help point me in the right direction? Thanks in advance. -
How to Annotate Nested Span Relationships and Reuse It for Multiple Filter Conditions?
I am trying to exclude nested foreign key fields from Django query. I have a relationship model. class Relationship(news_models.TimeStampedModel, RelationshipStatus): from_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='from_users') to_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='to_users') status = models.CharField(max_length=10, choices=RelationshipStatus.RELATIONSHIP_STATUSES) I wrote like this: Post.objects.filter( ~Q(Q(creator__from_users__to_user=user) & Q(creator__from_users__status='BLOCK')) & ~Q(Q(creator__to_users__from_user=user) & Q(creator__to_users__status='BLOCK')) ) But it does not work because this query excludes all the users who blocked or got blocked by at least one irrelevant user. I want something like this: Post.objects.filter( ~Q(creator__from_users=Subquery(Q(to_user=user) & Q(status='BLOCK'))) & ~Q(creator__to_users=SubQuery(Q(from_user=user) & Q(status='BLOCK'))) ) Or Post.objects.annotate(creator_from_users=F('creator__from_users')).annotate(creator_to_users=F('creator__to_users')).filter( ~Q(Q(creator_from_users__to_user=user) & Q(creator_from_users__status='BLOCK')) & ~Q(Q(creator_to_users__from_user=user) & Q(creator_to_users__status='BLOCK'))) ) How should I annotate or save the value in the middle and reuse it to filter nested foreign fields? -
How to filter Django object to get top X number of objects with highest property value
So I have a class called Hero with 150 objects. Each object has a property Winrate. I want to get the top 12 heros based on winrate. class Hero(models.Model): hero_name = models.CharField(max_length=20, default = 'Dota 2 Hero') hero_id = models.IntegerField() def __str__(self): return str(self.hero_id) def get_winrate(self): wins = len(Match.objects.filter(heros_won = Hero.objects.get(hero_id = self.hero_id))) losses = len(Match.objects.filter(heros_lost = Hero.objects.get(hero_id = self.hero_id))) if wins + losses != 0: return round((wins / (wins + losses)),2) else: return 0 winrate = property(get_winrate) I tried alot of filters but couldn't get it to work. -
advantages of generic view method over apiView
I am working on a big project and when it comes to the views.py, I was adviced by a friend to use apiViews over generic view or modelViewset. I would like to know what advantage a view method could have over others that makes it better to use in a big project over other methods. the project in question would have things like users making video posts and updating it, following other users, collaborating e.t.c. -
Django - Static files not found on ubuntu
I currently stuck on handling static files with django on lubuntu, keep receiving error 404, file not found. I've tried multiple possibilities that I've googled, but none of them worked in my case. I have my static files under static folder in my main project's folder. settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] STATIC_URL = '/static/' STATICFILES_DIR = [ STATIC_DIR, ] Could you give me advice what is the bast way to handle static files on ubuntu or if you see any solution in my case? -
get django inheriting templates from java
i'm new in django i want call the inheriting templates after click on image to new div i'm tried to add it but its not call its ok if used array text but django inheriting not work any help please // javascript <script type="text/javascript"> var djangoLink = {% include 'base/sceneForm.html' %}; function myFunction() { document.getElementById("Total").innerHTML= djangoLink ; } </script> // html <div id="Total"> </div> <img onclick="myFunction()"> -
Accessing .csv data from views file
I have a small Django app, and I'm trying to access data from a CSV file (static/blog/dat.csv, the static folder is at the same level as the templates folder and views.py; and everything is inside my blog app) so I can use it to plot a graph on the browser using Chart.js. Aside from not being able to do that, the app is working fine. I know I'm gonna need to pass some sort of context to the view function, but I don't know how I'd do that. Also, I have a couple of similar csv files, and using them as static files in my app seems simpler and easier than to add everything to a database to access them that way. # views.py from django.shortcuts import render from django.contrib.staticfiles.storage import staticfiles_storage import csv def rtest(request): url = staticfiles_storage.url('blog/dat.csv') with open(url, 'r') as csv_file: csv_reader = csv.reader(csv_file) for line in csv_reader: context += line return render(request, 'blog/r.html', context) # urls.py urlpatterns = [ # ... path('r-test/', views.rtest, name='blog-r-test'), ] Here is the error I'm getting: FileNotFoundError at /r-test/ [Errno 2] No such file or directory: '/static/book/dat.csv' I'm sure this is not the only error. I know that the way I'm … -
else (in an if else condition) not working
I have a javascript function that sends a XMLHttpRequest when a button is clicked, once the request is processed by the python code, I want the function to perform a task depending to the response of the python code. Specifically once the request is loaded request.onload calls a function that has an if else condition, however the else statement is not recognized and i get the error Uncaught SyntaxError: Unexpected token else Any clues about what that's happening? function clicked(param) { // Figure out how to get the name of the table to query const request = new XMLHttpRequest(); const id = param.id; const name = param.name request.open("POST", "/add_to_cart", true); const data = new FormData(); data.append("id", id); data.append("name", name); var csrftoken = getCookie('csrftoken'); request.setRequestHeader("X-CSRFToken", `${csrftoken}`); request.send(data); request.onload = () => { if (request.responseText === 0) { alert("Added to cart"); }; else { var array = document.getElementsByClassName("plus radius"); for (var i=0; i<array.length; i++) { array[i].style.display = "none"; }; alert("Added to cart, please choose your toppings"); }; }; return false }; -
Why am I receiving this Template error in my django tutorial?
I am currently working through the django polls tutorial and I keep receiving this error. I just can't seem to figure out how to fix it. I have tried watching multiple youtube tutorials, searched on stack for users having the same problem, and I can't seem to get anything to work.enter image description here -
how can I process to send generated pdf as attach mail in django?
for my homework, I need to send an attach file to e-mail. there I have some questions about attach file on django send mail: 1-is't possible to send it without save the PDF document in the DB? 2- how can I process to realise this function? In fact all helps consult didn't match. Definition of render_to_pdf utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None the generated function : views.py class GeneratePDF(View): context_object_name = 'services' template_name = 'pdf.html' def get(self, request, *args, **kwargs): template = get_template('configuration/pdf.html') f=Reservation.objects.all().filter(Q(valide=True, option__in=Option.objects.all().filter(Q(code_option='GTR', posseder_niveau__in=Posseder_Niveau.objects.all().filter(niveau_id = 1))))).order_by('date_du_jour_reserve') c = Plage_Horaire.objects.all() context = { "c":c, 'f':f, } html= template.render(context) pdf = render_to_pdf('configuration/pdf.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" %("12341231") content = "inline; filename='%s'" %(filename) download = request.GET.get("download") if download: content = "attachment; filename='%s'" %(filename) response['Content-Disposition'] = content return response return HttpResponse("Not found") -
Django: Casting Abstract Models
I have an abstract Django model that I use to create two other models. How can I avoid duplicating code when dealing with the different examples below (for example, when creating a Boxed cereal and a Bowled cereal I would like to avoid duplicating the function twice. class Cereal(models.Model): name = models.CharField() class Meta: abstract = True class Boxed(Cereal): pass class Bowled(Cereal): pass func some_func_boxed(name): boxed = Boxed.objects.get(id=1) boxed.name = "Captain Crunch" boxed.save() func some_func_bowled(name): bowled = Bowled.objects.get(id=1) bowled.name = "Lucky Charms" bowled.save() -
How to use the value of a model in another value of the same django model
I have a model Group that has a field maximum_capacity and a member field, what i want to do is to use the value the user enters in the field maximum capacity to set the max_choices for the member field. I am using Django2.2 and the max_choices option came from the MutiSelectField package i installed. I have tried converting to int using int() but gives the same error. class Group(models.Model): number_of_group_members = ((i, i) for i in range(2, 100)) members_choices = [(member.email, member.first_name + member.last_name) for member in CustomUser.objects.all()] maximum_capacity = models.IntegerField(choices=number_of_group_members, default='Specify group limit') members = MultiSelectField(max_choices=(i for i in range(maximum_capacity)), unique=True, choices=members_choices) I keep getting the Error: members = MultiSelectField(max_choices=(i for i in range(maximum_capacity)), TypeError: 'IntegerField' object cannot be interpreted as an integer -
Django session is not unique
I have a simple Nomenclature model and items in it. I have two functions add to cart and view cart (shown below). I can select and add items to the cart. It works well locally. When I host in a live server using nginx and uwsgi. The session selection is not unique. If I select items in a browser and use another (different computer) browser I can see the same selection in another system browser. Also there is a delay in either add to cart or view cart. How can I troubleshoot it? How can I make unique sessions? I use Django 2.1, SQLite def add_cart(request): ''' This will add the profiles to the cart ''' if request.method == 'POST': selected_values = request.POST.getlist('name', None) if selected_values is not None: request.session['list_names'].extend(selected_values) profile_length = len(selected_values) message_profile = "Selected {} proteins added to the cart".format(profile_length) messages.success(request, message_profile) request.session.modified = True return render(request,'nomenclature/search_page.html') else: request.session['list_names'] = selected_values request.session.modified = True profile_length = len(selected_values) message_profile = "Selected {} proteins added to the cart".format(profile_length) messages.success(request, message_profile) return render(request,'nomenclature/search_page.html') def view_cart(request): selected_values = request.session.get('list_names') ''' This will show the cart page with list of profiles ''' context = { 'nomenclatures': Nomenclature.objects.all(), 'selected_groups': selected_values, } if selected_values is … -
500 Internal Server Error in production - Django
I'm very new in django and I am in deploying phase of a project. But after all setup, it shows 500 internal server error and the apache2 error log says ImportError: No module named 'backend' I tried to edit wsgi.py as I thik this is the one giving this error this is content of my wsgi.py file import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings.dev') application = get_wsgi_application() the error log says ImportError: No module named 'backend'