Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
find out how api authenticate users Django
I am working with a MySQL database managed by a django app and an api on which I do not have access. I will find out later how the api works but I need to make this functionality now for a presentation. The passwords in the database are stored this way $2a$10$rA59QU2GsWR4v6hugdYhruxY0bgZYVLv6ncxRe3BiDJMEpK0A0huW - when user registers from the legacy app. From my django app, users register and passwords are stored this way $2b$12$koykshnEpT39MgciBp4FGepw.LnbHt2Kmqbfm4TSipX6FAVRVKdjW. Django app can authenticate and passwords are validated ok no matter how many iterations are there and prefix $2b$ or $2a$. But recently in order to access an api feature I've needed to log in the user from the api side, so if I authenticate user using dajngo's generated password hash, the api does not succeed to authenticate. The question is, What do I need to tackle in order to make it work? I have tried to change iterations from 12 to 10, did not work. Now I want to change the prefix to 2a, not sure if it will work but anyway. Next I found that the password can be hashed with or without null terminator -> correct me if Im wrong but I need to … -
How to transfer data from old database to new modified database in django?
I have old django project and new django project. I created dump file from database of old django. And also I made changes in tables and created new tables. Now I want to load that dump file to my new django app. I am facing errors when I firstly migrate then restore data or firstly restore then migrate.. When I do migration first, it says tables already exist. When I do restore first , it says django.db.utils.ProgrammingError: relation "django_content_type" already exists I use migrate --fake error goes but new tables are not created in database. I spent 3-4 days but could not succeed. Please, help me if you can. PS: my database is postgresql -
Django migrations error: dont create authomatically permissions and contenttypes
I work with django 1.8.7 and python 2.7 . I have peoblem with migrate. when I migrate my models , permission and contenttypes don't create automatically. error looks like this: Traceback (most recent call last): File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/core/management/base.py", line 222, in run_from_argv self.execute(*args, **options.__dict__) File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/core/management/base.py", line 252, in execute output = self.handle(*args, **options) File"/home/mariocesar/Proyectos/Crowddeals/crowddeals/core/management/commands/update_pe rmissions.py", line 29, in handle create_permissions(app, get_models(), options.get('verbosity', 0)) File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/contrib/auth/management/__init__.py", line 74, in create_permissions for perm in _get_all_permissions(klass._meta, ctype): File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/contrib/auth/management/__init__.py", line 28, in _get_all_permissions _check_permission_clashing(custom, builtin, ctype) File "/home/mariocesar/Proyectos/Crowddeals/env/local/lib/python2.7/site- packages/django/contrib/auth/management/__init__.py", line 49, in _check_permission_clashing for codename, _name in custom: ValueError: too many values to unpack and when I change migrations file like this: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.management import _get_builtin_permissions, _check_permission_clashing from django.db import migrations, models from django.conf import settings def _get_all_permissions(opts, ctype): """ Returns (codename, name) for all permissions in the given opts. """ builtin = _get_builtin_permissions(opts) custom = list(opts.permissions) if any(isinstance(el, basestring) for el in custom): custom = [custom] _check_permission_clashing(custom, builtin, ctype) return builtin + custom class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='JsonModel', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('data', models.CharField(max_length=1000000)), ('generatedtime', models.DateTimeField(auto_now_add=True, null=True)), ('title', models.CharField(max_length=200, null=True, … -
Failed to load resource: though the file is placed there
I am using python,To display image to a page,i am getting the below errors GET http://127.0.0.1:8000/static/neo4j/avatar1.png 404 (Not Found) 127.0.0.1/:30 GET http://127.0.0.1:8000/static/neo4j/logo-png-type.png 404 (Not Found) 127.0.0.1/:123 GET http://127.0.0.1:8000/static/neo4j/avatar2.png 404 (Not Found) 127.0.0.1/:143 GET http://127.0.0.1:8000/static/neo4j/avatar6.png 404 (Not Found) 127.0.0.1/:133 GET http://127.0.0.1:8000/static/neo4j/avatar4.png 404 (Not Found) 127.0.0.1/:138 GET http://127.0.0.1:8000/static/neo4j/avatar5.png 404 (Not Found) given the directory and images are available -
Javascript code doesn't work in Django project
I built an app using Django 3.2.3., but when I try to settup my javascript code for the HTML, it doesn't work, then I thought it could be the location of the static file the issue, and as you can see I have created two static files, with no successfull result. If you could lend me a hand I'll be very thankful. I'm using the following configuration: BASE_DIR = Path(__file__).resolve().parent.parent FORMULARIO_DIR = BASE_DIR / 'formulario' STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', FORMULARIO_DIR / 'static', ] Javascript settup in HTML {% load static %} <!DOCTYPE html> <html lang='es'> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href= "{% static 'formulario/style.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'scriptequipo.js' %}"></script> <title>Análisis de Infraestructura</title> </head> And here is how is organized the Django Proyect ├───formulario │ ├───migrations │ │ └───__pycache__ │ ├───static │ │ └───formulario │ ├───templates │ │ └───formulario │ └───__pycache__ └───Portfolio ├───static └───__pycache__ -
Django Media Files on Production without third party (Ex: S3 storage )
I have finished my private project, after I set debug to False, everything was broken, yet I fixed the static files with WhiteNoise but not working with media files. I have been searching and the answers are always the same... Use S3. Since I don't want to use S3, are there any solutions to store tons of images uploaded by the users -
error : set_model() missing 1 required positional argument: 'model'
I've created an emotion detection Model with resnet50 and I'm using the Adam optimizer. However, I get the following error TypeError: set_model() missing 1 required positional argument: 'model' And here's my code to create a model: # Build model on the top of base model model = Sequential() model.add(base_model) model.add(Dropout(0.5)) model.add(Flatten()) model.add(BatchNormalization()) # fully connected layer-1 model.add(Dense(128, kernel_initializer = 'he_uniform')) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.5)) # fully connected layer-2 model.add(Dense(64, kernel_initializer = 'he_uniform')) model.add(BatchNormalization()) model.add(Activation('relu')) model.add(Dropout(0.5)) # fully connected layer-3 model.add(Dense(32, kernel_initializer = 'he_uniform')) model.add(BatchNormalization()) model.add(Activation('relu')) # output layer model.add(Dense(7, activation = 'softmax')) # model Summary model.summary() # compile model model.compile(optimizer= 'Adam', loss='categorical_crossentropy', metrics=metric) # model fitting history = model.fit_generator(train_generator, validation_data=test_generator,epochs=60,verbose = 1,callbacks=callbacks) please help me -
Product is not adding in cart 'Django Administration'
I'm unable to add the product in cart. I want to see the product is adding to cart or not. but the process is not happening. I'm using Django as backend, PostgresSQL as DB and HTML, CSS and Javascript as backend. The Codes Goes here: views.py PRODUCT DETAIL class product_detail(View): def get(self, request, pk): product_detail = Product.objects.get(pk=pk) return render(request, 'detailpage/productdetail.html', {'product_detail':product_detail}) ADD TO CART def addProduct(request): user = request.user product_id = request.GET.get('product_id') product_cart = Product.objects.get(id=product_id) Cart(user=user, product=product_cart).save return render(request, 'cart/addtocart.html') urls.py app_name = 'main' urlpatterns = [ path('product_detail/<int:pk>', views.product_detail.as_view(), name='product_detail'), path('addProduct/', views.addProduct, name ='addProduct'), ] productdetail.html ... <form action="/addProduct"> <input type="hidden" name="product_id" value="{{product_detail.id}}" id="product_id"> <button type="submit" class="btn btn-info">Add</button> </form> ... models.py class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) def __str__(self): return str(self.id) url pattern in address bar after hitting add button http://127.0.0.1:8000/addProduct/?product_id=2342 But after this also the product is not adding in Django cart -
I'm not getting my code from index.html when extending base.html (django)
Base.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Question Time</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet"> {% block style %} {% endblock %} </head> <body> {% block content %} {% endblock %} </body> </html> Index.html {% extends "base.html" %} {% load render_bundle from webpack_loader %} {% block contend %} <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <h1>Test</h1> <!-- built files will be auto injected --> {% render_bundle 'app' %} {% endblock %} urls.py """QuestionTime URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path, re_path from django_registration.backends.one_step.views import RegistrationView from core.views import IndexTemplateView from users.forms import CustomUserForm # https://django-registration.readthedocs.io/en/3.1.2/activation-workflow.html urlpatterns = [ … -
How to render foreign key fields to Django forms like it shows on the admin panel?
class Members(models.Model): first_name= models.CharField(max_length=50, default='', blank=False) last_name= models.CharField(max_length=50, default='', blank=False) dob=models.DateField(blank=False) def __str__(self): return self.first_name class ContactDetail(models.Model): account = models.ForeignKey(Members, default=None, on_delete=models.CASCADE) telephone=models.CharField(max_length=15, default='', null=False) mobile=models.CharField(max_length=10, default='', null=False) class Qualification(models.Model): account = models.ForeignKey(Members, default=None, on_delete=models.CASCADE) degree=models.CharField(max_length=500, default=None) year_of_passing=models.CharField(max_length=4, default=None) college=models.TextField(default=None, null=True, blank=True) This is my model and I want to create a form that asks the user to fill in all the details, including the fields from the model that contains the foreign key to the 'Member' model. All I came across was MultipleChoice Field and ChoiceField, but that does not satisfy my requirements. Is there any way I can do it? -
You are trying to add a non-nullable field 'password' to user without a default
I am building a Django project in Docker Environment using below Docker YAML file: django_3.2.4: build: context: ./ImageBuild/ dockerfile: Dockerfile_Build_Django container_name: Django_3.2.4 depends_on: - Postgres_13.2 environment: - DJANGO_SUPERUSER_USERNAME=admin - DJANGO_SUPERUSER_PASSWORD=123456 - DJANGO_SUPERUSER_EMAIL=admin@abc.com networks: external_net: ipv4_address: 192.168.100.22 restart: always volumes: - ./IoTSite/:/usr/src/app/ - /etc/localtime:/etc/localtime:ro command: sh -c "python manage.py makemigrations && python manage.py migrate && python manage.py createsuperuser --noinput --no-input && rsync --daemon && gunicorn" And I created a Custom User Model as below: (with AUTH_USER_MODEL = 'IoTSite.User' added in settings.py) class User(AbstractUser): UserID = models.CharField('username:',help_text='required', max_length=20, primary_key=True,unique=True, blank=False) USERNAME_FIELD = 'UserID' First_Name = models.CharField('first_name:',max_length = 2) Last_Name = models.CharField('last_name:',max_length = 2) Date_Created = models.DateTimeField(auto_now_add=True, editable=False) #timestamps for creation, hidden from user input Date_Birth = models.DateField('Birthday:') Gender_Choice = [ ('Male','Male'), ('Female','Female'), ] Gender = models.CharField('Gender:',choices=Gender_Choice, max_length=1) When I run the container by command docker-compose up, it failed with below error: (and container keeps on restarting, I did not have opportunity to key in my selection) 2021-06-15T03:17:32.964281763Z WARNINGS: 2021-06-15T03:17:32.964284245Z IoTSite.Category: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. 2021-06-15T03:17:32.964287706Z HINT: Configure the DEFAULT_AUTO_FIELD setting or the IoTSiteConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. 2021-06-15T03:17:32.964300827Z IoTSite.Tag: (models.W042) Auto-created primary key used when … -
non_field_errors": ["Invalid data. Expected a dictionary, but got InMemoryUploadedFile."]
While create the data from postman, it show this error,"image":"non_field_errors": "Invalid data. Expected a dictionary, but got InMemoryUploadedFile." and how to upload multiply images at onetime through ModelViewSet class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'slug' parser_classes = [MultiPartParser, FormParser] class ProductImageSerializer(ModelSerializer): class Meta: model = ProductImage fields = ['id', 'image'] class ProductSerializer(ModelSerializer): image = ProductImageSerializer(required=True, many=True) class Meta: model = Product fields = '__all__' def create(self, validated_data): product = Product.objects.create(**validated_data) image_data = validated_data.pop('image') if image_data.is_valid(): for img in image_data: image = ProductImage.objects.create(product=product, image=img) product.save() return product class Product(Core): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='product') brand = models.ForeignKey(Brand, on_delete=models.RESTRICT, related_name='product') name = models.CharField( _('Product Name'), max_length=255, validators=[ MinLengthValidator(30), MaxLengthValidator(255), ], help_text=_('Title should be Minimum 30 Characters'), ) slug = models.SlugField(unique=True, blank=True) is_active = models.BooleanField(default=True) is_approved = models.BooleanField(default=False) class ProductImage(Core): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='image') image = models.ImageField(upload_to=path_and_rename) -
How do I find the class that RelatedManager is managing when the QuerySet is empty?
I have two models that are related. From the object of one, I want to get the class name of the other. Currently, I'm doing it this way: associated_model = getattr(object_specific, associated_model_str) associated_model_instance = associated_model.all().first() if associated_model_instance: associated_model_name = associated_model_instance.__class__.__name__ In this case, object_specific is an object of a model. associated_model_str is the name of the attribute in that model that has a reference to the second model. When I get the attribute into associated_model, this variable contain the RelatedManager for the second model. If I do .all().first() I will get an object from that model, from where I can get the class name by checking the attribute .__class__.__name__. The problem is that sometimes I don't have any instances of the second model in the database associated to the instance of the first model. In other words, the .all() comes empty. So I don't have an instance of the second class to get the class name. How can I get that class name directly from the RelatedManager? -
how to prevent new element being appended repeatedly in javascript function?
Currently i have a java-script function like this: <script type="text/javascript"> function select_device(device) { var mylink = window.location.href + "&name=" + device.value; window.location.replace(mylink); window.history.back } </script> when a variable pass in it will add as a new element into the url. Is there any way that i could possibly pass the variable in smartly as it will not just append repeatedly to the existing address? I have tried to do it like const url = window.location window.location.replace(url.hostname + url.pathname + url.search + "&name=" + device.value) But it doesn't solve the problem. -
The Django's Authenticate method in my login view doesn't work properly. It doesn't even authenticates the users which the admin creates
I first created a custom user model by inheriting AbstratctBaseUser: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils import timezone from .manager import FirstManager #Making custom User model class MyRegistration(AbstractBaseUser, PermissionsMixin): location_list=[ ('Solapur', 'Solapur'), ('Latur', 'Latur'), ('Dhule', 'Dhule'), ('Akola', 'Akola'), ('Nashik', 'Nashik') ] username=models.CharField(max_length=10, unique=True) email=models.EmailField(unique=True) first_name=models.CharField(max_length=150) last_name=models.CharField(max_length=150) location=models.CharField(max_length=10, choices=location_list, default='Latur') designation=models.CharField(max_length=70) is_active=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) start_date=models.DateTimeField(default=timezone.now) last_login=models.DateTimeField(null=True) USERNAME_FIELD='username' REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation'] objects=FirstManager() def __str__(self): return self.username My custom manager: from django.contrib.auth.models import BaseUserManager class FirstManager(BaseUserManager): use_in_migrations=True def create_user(self, username, email, first_name, last_name, location, designation, password, **extra_fields): if not username: raise ValueError('Username is required!') email=self.normalize_email(email) user=self.model(username=username, email=email, first_name=first_name, last_name=last_name, location=location, designation=designation, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, username, email, first_name, last_name, location, designation, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True.') return self.create_user(username, email, first_name, last_name, location, designation, password, **extra_fields) The Registration form: from django import forms from .models import MyRegistration from django.contrib.auth.forms import UserCreationForm #Signup form class MyRegistrationForm(UserCreationForm): password2=forms.CharField(label='Confirm', widget=forms.PasswordInput) class Meta: model=MyRegistration fields=['username', 'first_name', 'last_name', 'email', 'location', 'designation'] The Registration view in views.py: def signup(request): if request.method=='POST': if request.POST.get('password1')==request.POST.get('password2'): try: … -
What is the equivalent of " LIKE concat('%', ?, '%') " in Django?
I need to convert MariaDB raw queries to Django's default MySQL backend raw queries. MariaDB uses ? for the parameterization and the Django-MySQL connector uses %s instead. I know that for LIKE concat(?, '%') we can use LIKE %s and it will work. But how about LIKE concat('%', ?, '%') ? What would be the equivalent for Django? -
How to perform a parametrized raw query in Django?
I'm reading the official Django documentation, but I can't find an answer to my question. Right now I have this query implemented, working with a custom MariaDB connector for Django: results = [] cursor = get_cursor() try: sql="SELECT a.*, COALESCE( NULLIF(a.aa, '.'), NULLIF(a.gen, '.') ) AS variant, b.*, c.* FROM `db-dummy`.sp_gen_data c JOIN `db-dummy`.gen_info a ON a.record_id = c.gen_id JOIN `db-dummy`.sp_data b ON b.record_id = c.sp_id WHERE a.gene_name LIKE concat(?, '%') AND a.report_notation LIKE concat('%', ?, '%') AND b.sp_id LIKE concat(?, '%');" data = (gen, var, sp) cursor.execute(sql, data) except mariadb.Error as e: print(f"Error: {e}") columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results It works, but now I need to adapt this query to the django's default MySQL backend. What I've tried: results = [] cursor = get_cursor() sql="SELECT a.*, COALESCE( NULLIF(a.aa, '.'), NULLIF(a.gen, '.') ) AS variant, b.*, c.* FROM `db-dummy`.sp_gen_data c JOIN `db-dummy`.gen_info a ON a.record_id = c.gen_id JOIN `db-dummy`.sp_data b ON b.record_id = c.sp_id WHERE a.gene_name LIKE %s AND a.report_notation LIKE %s AND b.sp_id LIKE %s;" data = ('{}%'.format(gen), '{}%'.format(var), '{}%'.format(sp)) cursor.execute(sql, data) columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): … -
Uploading a canvas (web camera snap) taken on client's side (with javascript) to Django's server side
I am new with Django, and I need to take a snap on the client's side with js [done in 1.] and send it to my server [trial in 2.] so later I can manipulate it on views.py. By now, I can send images to the server (media/images), but only if I use that "Django's button" that is auto-generated through forms/models and views, which forces the user to choose a pic from his computer. The problem is that I need it to be automatized (so the program must "grab" the snap, name it (as snap.jpg, for example), "put it somehow on that button", and upload it). I have been searching and trying for the last 3/4 days, and this was the best I could do... Please take into consideration that I am a newbie... So I really appreciate it if your answers came in explicit code mode... Thanks in advance! (: Code is below: 1. player1.html <video id="video"></video> <canvas id="canvas"></canvas><br> <button onclick="snap();">Snap</button> JS const video = document.getElementById('video'); const canvas = document.getElementById('canvas'); const context = canvas.getContext('2d'); navigator.mediaDevices.getUserMedia({video: true}) // request cam .then(stream => { video.srcObject = stream; // don't use createObjectURL(MediaStream) return video.play(); // returns a Promise }) function snap () … -
FCGI htaccess handler: command not found
i am finishing with the configuration of my django project in ssh, after installing Django and two other libraries (flup==1.0.2, django-wsgi) It asks me to create the . htaccess file with the settings of the FCGI Handler and redirection to the index.fcgi file with the following command: AddHandler fcgid-script .fcgi RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] The problem is that at the time of writing in the terminal AddHandler fcgid-script .fcgi shows me the following error: jailshell: AddHandler: command not found. And I was researching but can't find anything concrete to resolve this error. Do I have to type the whole command together? I leave a capture of the terminal as I can't copy its contents. Thank you -
Django: How to show foriegn key's fields in template
I have the following model class Devices(models.Model): ... device_user = models.ForeignKey( 'User', related_name="%(app_label)s_%(class)s_user", on_delete=models.PROTECT, ) Now I have def show_devices(request): devices = Devices.objects.all() return render(request, 'device.html', dict(devices=devices)) Now i am trying to access the username in template {{devices.device_user.username}} BUt it shows blank -
Django Rest Framework - AttributeError: 'function' object has no attribute 'get_extra_actions'
Getting "AttributeError: 'function' object has no attribute 'get_extra_actions'" error with Django 3.2.4 and djangorestframework 3.12.4 Logs: backend | Traceback (most recent call last): backend | File "manage.py", line 22, in <module> backend | main() backend | File "manage.py", line 18, in main backend | execute_from_command_line(sys.argv) backend | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line backend | utility.execute() backend | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute backend | self.fetch_command(subcommand).run_from_argv(self.argv) backend | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv backend | self.execute(*args, **cmd_options) backend | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute backend | output = self.handle(*args, **options) backend | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped backend | res = handle_func(*args, **kwargs) backend | File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle backend | self.check(databases=[database]) backend | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check backend | all_issues = checks.run_checks( backend | File "/usr/local/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks backend | new_errors = check(app_configs=app_configs, databases=databases) backend | File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config backend | return check_resolver(resolver) backend | File "/usr/local/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver backend | return check_method() backend | File "/usr/local/lib/python3.8/site-packages/django/urls/resolvers.py", line 412, in check backend | for pattern in self.url_patterns: backend | File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ backend | res = instance.__dict__[self.name] = self.func(instance) backend | … -
How do I fix ToDoList is not in main.models in Django
So when I do >>>ToDoList.objects.all() I get <QuerySet [<ToDoList: ufrz's list>]> But when I do >>>ToDoList.objects.get(id=1) I get Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\ufrz9\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\ufrz9\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( main.models.ToDoList.DoesNotExist: ToDoList matching query does not exist. How do I get the id=1 command to work, I'm trying ultimately have it so when I do /ufrz's list I get my item and todolist -
Django: Return all users based on number of occurrences in another table
Given the two models class User(AbstractBaseUser, PermissionsMixin): Name = models.CharField(max_length=65) trial_days = models.IntegerField(default=21) ... class BlogPost(models.Model): user = models.ForeignKey('User', on_delete=models.CASCADE) text = models.TextField(max_length=65) Date = models.DateField() How can I return all users that have at-least three blog posts? I am currently iterating all the users and checking if they have three posts however I believe there may be a more pythonic way to do using Django.. -
CommandError: Unable to find a locale path to store translation for file manage.py after adding additional setting COUNTRIES_OVERRIDE
I am trying to translate just one specific country for django-countries and my language (zh-hant) is yet to be translated. I tried to add the example in documentation COUNTRIES_OVERRIDE = { "NZ": _("Middle Earth"), "AU": None, "US": { "names": [ _("United States of America"), _("America"), ], }, } to the end of my settings.py and after that this error occurs: CommandError: Unable to find a locale path to store translations for file manage.py yet reverting this setting is fine. I don't quite understand how adding this setting makes it unable to find the existing locale path. My settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] SITE_ID = 1 # Application definition INSTALLED_APPS = [ "...", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", "django_countries", "django_filters", "django_registration", "multiselectfield", ] MIDDLEWARE = [ "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", "django.middleware.common.BrokenLinkEmailsMiddleware", ] ROOT_URLCONF = "mysite.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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 = "mysite.wsgi.application" # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": … -
Create-react app integration with django backend vs babel and webpack pipeline
I've been trying to get up a react and django application. First, I had followed this set of videos here: https://www.youtube.com/watch?v=6c2NqDyxppU&list=PLzMcBGfZo4-kCLWnGmK0jUBmGLaJxvi4j&index=3. There was a bunch of commands that you can see in the description that needed to be run in as well as a lot of copy pasting configuration files. Later, my friend told me that create-react-app existed and would set up everything needed with just one command. I tried it, and it worked really well. However, there were issues with connecting it to django. The files that came out of create-react-app were different to the ones shown in the video and when I tried searching it up, a few solutions said to use npm run build and pass the build folder into django. Running a build takes quite a long time and it is not automatic as it was when I had the webpack and babel system. What am I supposed to do to configure create-react-app so that I can get it to update automatically and get it into django. Some places said that I could edit the config files when I do npm run eject. There is a problem that the package.json files in the tutorial project and …