Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List of all database as well as tables available in sqlite3
I am trying to get the list of all the databases that I have in sqlite3. Here I am trying only to print all the databases name available to me and once clicked on a particular database, I will print all the tables available under that particular database. Here is my views code snippet: def analyzer(request): serv = sqlite3.connect(host = "localhost", user = "root", passwd = "abcdefg") c = serv.cursor() c.execute("SHOW DATABASES") l = c.fetchall() print (l) # l = [ i[0] for i in l ] # print (l) return render(request, 'analyzer.html') -
the KeyError: 1 problem , whats the problem?
in this code : for item in orderOFsssReserve: fforderOFsssReservefff=[] for item0 in orderDoubles1: if(item.studentidof== item0.userid): orders_student[j].setdefault(j, []).append(item0) break in the line of code : orders_student[j].setdefault(j, []).append(item0) i have this error : KeyError: 1 help me please -
Multiple requirements.txt files for django (production vs development)
I'm currently rewriting a few things and wanted to narrow down our requirements we use in production. We are primarily building Django projects/applications. Right now we use just one requirements.txt file in the project root that includes all installed libraries needed for both development and production. This requirements.txt file includes things like: pytest pytest-cov pytest-django flake8 factory-boy selenium Those things are never utilized on a production box... so it doesn't make sense to be installing them on production boxes. What is the best way to manage multiple requirements.txt files? Is it easiest to just rename them? production-requirements.txt development-requirements.txt Then just pip install production-requirements.txt on the production box? Are there other options? It seems trying to manage multiple .txt files would get old after a while when updating libraries and such. I've seen mention of Poetry - but that seems a bit like overkill for such a small use case such as this - or maybe it's just right thing? Trying to streamline things a little and reduce the amount of additional libraries we are loading in production where we don't need them vs. dev where we need them. Any/all help is welcome. -
Django - Creating & searching a custom user model
I have created my own custom user model, to override the built in one. # models.py class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email Originally, when I wanted to search the database, i would import from django.contrib.auth.models import User, and then do.. # create new user new_user = User() # Search existing users Users.objects.find() My question is, in a world where im now using my own custome user model, how do I do the equivalent? Do i have to from model import CustomUser and then use that instead? Thanks, -
How to safely redirect to HTTPS on Django app not behind a proxy?
essentially, I want to turn SECURE_SSL_REDIRECT to true. but reading through the django docs, I get the impression this can compromise the projects security if it's not behind a proxy. am I understanding that correctly, and if so, how should I go about doing http->https redirects when not behind a proxy? thanks! -
What frameworks should I choose for app development?
I’m currently learning Django and from what I understand Django is a backend language. The thing I can’t understand is that Django offers template rendering which in fact would be the front end part. Am I wrong here? Is there a way to use Django along with a frontend such as React or Vue? Also, what backend language would you recommend? I’ve read a lot about Java Spring and Ruby on Rails and am thinking of transferring to one of them. -
Update An Attribute in A Model (Table) Depending on the Previous Value of the Attribute Django
I have an attribute amount in some model Stock. If I want to set all the value of amount to 10 for all the rows, I will simply run: Stock.objects.update(amount=10) However, I want to update all the amounts in such way that 1 is added to all the amounts. So, something like this: Stock.objects.update(amount=amount + 1) which is not possible, off course. But, I need something like this. -
in my code i have the KeyError: 1 problem , whats the problem?
for item in orderOFsssReserve: fforderOFsssReservefff=[] for item0 in orderDoubles1: if(item.studentidof== item0.userid): orders_student[j].setdefault(j, []).append(item0) break im my code i have this error : KeyError: 1 help me please -
ProgrammingError at / relation "posts_post" does not exist LINE 1: ...evious_post_id", "posts_post"."next_post_id" FROM "posts_pos
I'm Sorry to ask again, but i haven't gotten any solutions. my django blog works fine locally but after deploying to heroku, i started having an error. the error states "ProgrammingError at / relation "posts_post" does not exist LINE 1: ...evious_post_id", "posts_post"."next_post_id" FROM "posts_pos..." please what can I do to resolve this? -
Cannot access my AWS Lightsail Django application from public IP
I am trying to host my Django application from my aws lightsail public IP. I have deployed my application to folder: /opt/bitnami/projects/spirit/spirit. and defined and activated the virtual host at /etc/apache2/sites-available/spirit-vhosts.conf. My spirit-vhosts.conf file is: <IfDefine !IS_spirit_LOADED> Define IS_spirit_LOADED WSGIDaemonProcess sample python-home=/opt/bitnami/python python-path=/opt/bitnami/projects/spirit processes=2 threads=1 5 </IfDefine> <VirtualHost 127.0.0.1:80 _default_:80> ServerAlias * WSGIProcessGroup spirit Alias /robots.txt /opt/bitnami/projects/spirit/static/robots.txt Alias /favicon.ico /opt/bitnami/projects/spirit/static/favicon.ico Alias /static/ /opt/bitnami/projects/spirit/static/ <Directory /opt/bitnami/projects/spirit/static> Require all granted </Directory> Alias /media/ /opt/bitnami/projects/spirit/media/ <Directory /opt/bitnami/projects/spirit/media> Require all granted </Directory> WSGIScriptAlias / /opt/bitnami/projects/spirit/spirit/wsgi.py <Directory /opt/bitnami/projects/spirit/spirit> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> However, i cannot access my website from public IP. I have also added port 8000 as custom TCP in my aws lightsail network rules. When i perform sudo wget 127.0.0.1:80 i do get the correct response in an html file. What am i missing? -
reset_value does not reset the value on reaching upper limit on get_next_value
The steps are as follows: from sequences import get_next_value, get_last_value get_next_value('nu', initial_value=0, reset_value=1000) l = [get_next_value('nu') for i in range(1001)] Can one help what is wrong here? The requirement is to generate a sequence of numbers and set the counter to the initial value after it reaches an upper limit. The library used is django-sequences -
Django does not retrieve static files
I need to work with Sql Server so I am using Django==2.1. However, I am encountering a problem with the static files. I have read previous posts but none of them seem to work in my case. Project Structure - A: Management Dashboard -- B: Main App ----- C: migrations ----- C: static ----- C: admin.py ----- C: apps.py . . ----- C: views.py -- B: Management Dashboard ----- C: settings.py ----- C: urls.py ----- C: wsgi.py -- B: templates -- B: db.sqlite3 -- B: manage.py My settings.py file looks like: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MainApp.apps.MainappConfig', 'ManagementDashboard', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' My base.html file looks like this: {% load static %} <html ln="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Management Dashboard</title> <!-- Bootstrap CSS CDN --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous"> <!-- Our Custom CSS --> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> </head> <body> <div class="wrapper"> <!-- Sidebar --> <nav id="sidebar"> <div class="sidebar-header"> <h3>AVS</h3> </div> <ul class="list-unstyled components"> <p>Management Dashboard</p> <li class="active"> <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle"><i class="fa fa-home" aria-hidden="true"></i> Home</a> <ul class="collapse list-unstyled" id="homeSubmenu"> <li> <a href="#">Home 1</a> </li> <li> <a href="#">Home 2</a> </li> <li> … -
Python function does not recognize argument
I'm trying to DRY my unittest code by aggregating some common object creation in a super class that inherits from Django TestCase class. Currently the object creation is in a child class directly inherited from TestCase. Currently: class ExperimentQuestionnaireTest(ExperimentTestCase): def setUp(self): super(ExperimentQuestionnaireTest, self).setUp() exec(open('add_initial_data.py').read()) self.user, self.user_passwd = create_user(Group.objects.all()) The script in add_initial_data.py creates the Group objects. To be: class ExperimentTestCase(TestCase): def setUp(self): super(ExperimentTestCase, self).setUp() exec(open('add_initial_data.py').read()) self.user, self.user_passwd = create_user(Group.objects.all()) class ExperimentQuestionnaireTest(ExperimentTestCase): def setUp(self): super(ExperimentQuestionnaireTest, self).setUp() The create_user function is in a separate file and in both cases it's called normally. But in the second case the argument Group.objects.all(), that is a QuerySet, is not passed to the create_user function. def create_user(groups=Group.objects.none(), username=None, force_password_change=False): # code goes here When calling create_user after the changes in To be section groups is getting the default parameter instead of the Group.objects.all() queryset. I didn't understand why this is happening. What I'm missing? -
How to reduce selecting field for database performance when calling instance dot field in django orm?
When need to check a field value of an instance when use dot(.) for accessing the field as follows. class store(models.Model): ........ is_open = models.BooleanField(defrault=False) ........ class User(AbstractBaseUser): ........ store = models.ForeignKey(Store) ........ I need to check the value of is_open in some API I do as follows, request.user.store.is_open In this case, django performs a select query with all fields but I only need the is_open field. How can I only select only a single field (is_open in this case) instead of selecting all fields? -
Django get possible recipes from table of ingredients
at the moment I have a project where I need to get possible recipes from a database. There is one table which contains ingredients each with an id of the recipe the model looks like this: class Ingredients(models.Model): ingredientid = models.AutoField(db_column='IngredientID', primary_key=True, blank=True) recipeid = models.ForeignKey('Recipes', models.DO_NOTHING, db_column='RecipeID', blank=True, null=True) amount = models.CharField(blank=True, null=True, max_length=100) unit = models.CharField(blank=True, null=True, max_length=100) unit2 = models.CharField(blank=True, null=True, max_length=100) ingredient = models.CharField(db_column='Ingredient', blank=True, null=True, max_length=255) class Meta: managed = False db_table = 'Ingredients' And the database looks like this (You can ignore the amount and unit columns). And there is another table which contains the ingredients which the user has and each with an id of the user. The model looks like this: class UserIngredient(models.Model): _id = models.AutoField(primary_key=True) user_id= models.IntegerField() ingredient = models.CharField(max_length=255, null=False) class Meta: managed = True db_table = 'UserIngredients' And my question is how can I get the id for all the recipes the user has the ingredients for? -
How can I render Foreignkey Data or fields in Vuejs with django rest framework?
I'm learning to use Vuejs with Django rest framework so don't mind me if you find this question ignorant. Let's say I have 2 models Class Department(models.Model): name = models.CharField(..) Class Subject(models.Model): subject = model.CharField(..) department = models.ForeignKey(Department, ...) and forms like these Class DepartmentForm(models.Model): Class Meta: model = Department fields = ['name',] Class SubjectForm(models.Model): Class Meta: model = Subject fields = ['subject', 'department'] So If we render SubjectForm in regular django template the department field within SubjectForm will be rendered as CharField with choices and that choices are the data that we input into DepartmentForm. My question is how can we do that in Vuejs? How can we get the data from the foreinkey and display it inside the form as choices as we do in regular django template? I have been trying to google it and haven't find any example for that yet. -
Replace Null value of django objects with default value
I would like to replace null value in my django objects with the default value : Example : class Buy(models.Model): created = models.DateTimeField(null=True, blank=True, editable=False,default=timezone.now) modified = models.DateTimeField(null=True, blank=True,default=timezone.now) name = models.CharField(null=True,blank=True, max_length=200,default='') Here is my script : for buy in Buy.objects.all(): for f in Buy._meta.get_fields(): field = eval("buy." + f.name+" is None") if field: field = Buy._meta.get_field(f.name).get_default() buy.save() but when i make a json export with dumpdata i still have "name" : null, in my json for a lot of objects instead of "name": "" . I don't understand my script for migrating the null value of my object to "" seems to be correct. Regards -
How to save and retrieve a file on Heroku server for a Django App?
I have an application which is supposed to overlay name and date on an image Certificate_0001.jpg stored locally to output a pdf certificate using the function download (response, name, date). The application is deployed on Heroku, works fine locally, but once deployed, the location of Certificate_0001.jpg changes which is why the function is unable to overlay text and generate a pdf. How can I find the location of files stored in heroku server so I can access them? I have more than 300 student objects in my models for whom this app will generate graduation certificates, which is why storing the image for each object is not sustainable. Rather, retreving their names and graduation dates, and superimposing them on one image is more doable and takes less space. Views.py def download (request, date, name): x = date.split(" ") date = f"29 {x[3]} {x[4]}" try: image = Image.open("certificates\static\certificates\Certificate_0001.jpg") except: return HttpResponse ("image did not load") font_type = ImageFont.truetype('arial.ttf', 70) font_type_2 = ImageFont.truetype('arial.ttf', 35) draw = ImageDraw.Draw(image) draw.text(xy=(600, 740), text=name, fill=(0,102,0), font=font_type) draw.text (xy=(330, 1230), text=date, fill=(0,102,0), font=font_type_2) try: image.save(f'certificates\static\certificates\{name}.pdf', "PDF", resolution=100.0) except: return HttpResponse("pdf did not save") try: with open(f'certificates\static\certificates\{name}.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = f'inline;filename=NFDP-{name}.pdf' return … -
how can I change alowed host to mysite.com:8000
I want to open mysite.com:8000 but I cant!!!! what should I do? settings.py DEBUG = True ALLOWED_HOSTS = ['mysite.com', 'localhost', '127.0.0.1'] -
Django/React Deployment only works if I set DEBUG=True & STATICFILES_DIRS not a list
Trying to deploy my react frontend with django backend to pythonanywhere (PA) but get the following outcomes with the below 3 settings: DEBUG=True, STATICFILES_DIRS=[os.path.join(BASE_DIR, 'build/static')] - (Blank white screen) PA server log: File "/home/coot3/.virtualenvs/venv/lib/python3.8/posixpath.py", line 76, in join a = os.fspath(a) TypeError: expected str, bytes or os.PathLike object, not list Chrome console: Refused to execute script from 'http://mysite.pythonanywhere.com/static/js/main.446b4eaa.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. DEBUG=True, STATICFILES_DIRS=os.path.join(BASE_DIR, 'build/static') - (Website works as intended) DEBUG=False, STATICFILES_DIRS=os.path.join(BASE_DIR, 'build/static') - (Blank white screen) No issues in PA Server log Chrome console: Refused to execute script from 'http://mysite.pythonanywhere.com/static/js/main.446b4eaa.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I have the react app build folder in my django root folder and link to reacts index.html as a template view in urls.py. Here is my settings.py: from pathlib import Path import os import environ env = environ.Env( DEBUG=(bool, False) ) environ.Env.read_env() DEBUG = False SECRET_KEY = env('SECRET_KEY') BASE_DIR = Path(__file__).resolve(strict=True).parent.parent HOSTS = ['coot3.pythonanywhere.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES … -
Proper way to make advanced search in django
After reading and testing many posts, answers and tips, I decided to write down the way I made my search in my Django project to help others. It's in hungarian. models.py First thing fist, I have a model (called Igeny)with multiple attributes: class Igeny(models.Model): Cim = models.CharField(max_length=150, verbose_name="Igény címe") Igenylo = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Igénylő", blank=True, null=True) Igenyles_tartalom = models.TextField(verbose_name="Igénylés leírása") Status = models.IntegerField(default=0, verbose_name="Igénylés status") Allapot = models.CharField(default="Piszkozat", max_length=255, verbose_name="Igénylés állapota") UID = models.CharField(max_length=150, default="") Email = models.EmailField(default="xyz@xyz.hu") Phone = models.CharField(max_length=50, default="", null=True, verbose_name="Telefonos elérhetőség") Indoklas = models.TextField(default="", verbose_name="Igény indoklása") views.py In the views.py, fist I filtered the list of results with the Q object, then passed the results to a self created filter called IgenyFilter: def search_results(request): igeny_list = Igeny.objects.filter(Q(Ugyvezeto=request.user.profile) | Q(BeszerzesVezeto=request.user.profile) | Q(Igazgato=request.user.profile) | Q(EgysegVezeto=request.user.profile) | Q(Igenylo=request.user)).order_by('Status') igeny_filter = IgenyFilter(request.POST, queryset=igeny_list) igeny_lista = igeny_filter.qs.order_by('-Cim') return render(request, 'catalog/search_results.html', {'filter': igeny_filter, 'igeny': igeny_lista}) For this IgenyFilter, I made a filter.py: filter.py class IgenyFilter(django_filters.FilterSet): Cim = django_filters.CharFilter(field_name="Cim", lookup_expr='icontains', label='Igény címe (tartalmazza)') # Mindet listázza, amiben benne van a beírt szó Igenyles_tartalom = django_filters.CharFilter(field_name="Igenyles_tartalom", lookup_expr='icontains', label='Igénylés tartalma (tartalmazza)') # Mindet listázza, amiben benne van a beírt szó Igenylo = django_filters.CharFilter(field_name="Igenylo__first_name", lookup_expr='icontains', label='Igénylő neve') # Mindet listázza, amiben benne van a beírt szó … -
Displaying docker image tag/version inside Django frontend
I want to display the latest tag of my app's docker image on the frontend of my django application so that the users see the same app version as tagged in the docker image. Any ideas on how to achieve this? -
how to rewind or forward video on html
<!DOCTYPE html> <html> <body> <video width="1000" height="500" poster = "/media/4x3.jpg" autoplay muted loop playsinline controls> <source src="/media/11.mp4" type="video/mp4"> Your browser does not support HTML video. </video> <a href="/media/test.pptx" download><p>Download</p></a> </body> </html> i use this code but cannot rewind or forward the video. -
In django, login page content is not displaying only navbar is visible
Screenshots: Login Page screenshot Login Page html code Project level url file base.html page which contains the login link in navbar -
Cannot assign content_type" must be a "ContentType" instance
I am trying to implement a comment system to my blog, but have been getting an error when tying to assign content_type to the initial data thats going with the comment.. i have my sample code below #Comment app model class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() parent = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE) content = RichTextField() #Blog app model class Song(models.Model): ... ... @property def get_content_type(self): content_type = ContentType.objects.get_for_model(self.__class__) return content_type #Blog Views class SongDetail(ModelFormMixin, DetailView): model = Song form_class = CommentsForm def get_initial(self): obj = self.get_object() return { 'content_type': obj.get_content_type, 'object_id': obj.object_id } def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return redirect('music:obj.get_absolute_url()') form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)