Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django admin.autodiscover() import order on urls file
I cloned a sample app for django and run code inspection and found that admin.autodiscover is called before importing the views file, that's used for the patterns later: from django.contrib import admin from django.urls import path admin.autodiscover() import hello.views urlpatterns = [ path("", hello.views.index, name="index"), ... ] This triggers a PEP8 code style warning as the imports are not all on the top of the file. I'm afraid that moving it may have unintended side effects. Is that the case? -
Adding whitenoise to django gives an "ImproperlyConfigured: WSGI application" error
My application works if I were not to add "whitenoise.middleware.WhiteNoiseMiddleware" into the MIDDLEWARE in settings.py but if I were to add it back, then it would not work and would give this error django.core.exceptions.ImproperlyConfigured: WSGI application 'story_4.wsgi.application' could not be loaded; Error importing module. This is what is inside my wsgi.py file #wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'story_4.settings') application = get_wsgi_application() Any answer is appreciated. -
psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known
docker-compose run web python3 manage.py migrate WARNING: Found orphan containers (books_webapp_1) for this project. If you removed or renamed this service in your compose file, you can run this command with the --remove-orphans flag to clean it up. Starting books_db_1 ... Starting books_db_1 ... done Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/psycopg2/init.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not translate host name "db" to address: Name or service not known -
Unable to get image data in an API along with json data for registration
I want to create a register API in which I have username,email, password input along with an image field.I am unable to receive and process the data properly.The default user class is extended to store image field. I have this extended user model:- from django.contrib.auth.models import User import os def get_upload_path(instance, filename): fileName, fileExtension = os.path.splitext(filename) return os.path.join("user_%s" % instance.user.username,"user_{0}.{1}" .format(instance.user.username,fileExtension)) # Create your models here. class Userprofile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) display_picture=models.ImageField(upload_to=get_upload_path) has_voted=models.BooleanField(default=False) voted_item=models.CharField(max_length=200,default='none') def __str__(self): return self.user.username These are the serializers:- from django.contrib.auth.models import User from .models import Userprofile class UserprofileSerializer(serializers.ModelSerializer): class Meta: model=Userprofile fields=['display_picture'] class UserSerializer(serializers.ModelSerializer): class Meta: model=User fields=['username','email','password1','password2'] this is the path/url:- path('register',views.FileUploadView.as_view(),name='Register'), this is the view:- @csrf_exempt class FileUploadView(APIView): parser_classes=[MultiPartParser,FormParser] def register(self,request): display_picture=request.FILES["display_picture"] data=json.loads(request.data["data"]) #saving data using serializers return JsonResponse({'message': "Registered Successfully!"},status=200) I am getting this issue which says:- path('register',views.FileUploadView.as_view(),name='Register'), AttributeError: 'function' object has no attribute 'as_view' -
how to pass image file from database to html in django project
I tried many solution to solve it. But I can't fix and resolve. I can't able to pass the image file of my users to my html page. But I can able to access and pass all elements from database of a specific user. When I try to access the Image file of a user, it just returns a file path of the image. Please help me to resolve it. models.py class registration(models.Model): First_Name =models.CharField(max_length=50) Last_name = models.CharField(max_length=50) Phone_number = models.BigIntegerField() Email_id = models.EmailField() Password = models.CharField(max_length=20) Conform_Password = models.CharField(max_length=20) Register_No = models.BigIntegerField(primary_key=True) profile_pic = models.ImageField(upload_to="Profile") def __str__(self): return self.First_Name views.py def login(request, *args, **kwargs): if request.method == 'POST': user_Name=int(request.POST["stu_uname"]) pass_word=request.POST["stu_pwd"] get_user_name = registration.objects.filter(Register_No = user_Name).exists() if get_user_name is True: check_pwd = registration.objects.values('Password').filter(Register_No = user_Name) for check in check_pwd: pwd = check['Password'] if pwd == pass_word: user_objects = get_objects(user_Name) return render(request, "stu_profile.html", {'userObj': user_objects}) else: return HttpResponse("<h1> Password is incorrect</h1>") else: return HttpResponse("<h1> User name is incorrect </h1>") return redirect('student') def get_objects(name): check_objects = registration.objects.values().filter(Register_No = name) for check in check_objects: values = check return values HTML PAGE <div class="pro_pic"> <img src = "{{userObj.profile_pic}}"> <div> <p> {{userObj.First_Name}} {{userObj.Last_name}} </p> </div> </div> Settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'Pictures/') MEDIA_URL = '/Pictures/' -
Django no module named import_exportquestions
I am new to Django. I am trying to import questions from an excel file to my sqllite db. The steps i made is the following: 1) I have created a new env and installed django-import-export in it 2) started a project webload in Django 3) Created an app with name questions that defines the model Question like this from django.db import models # Create your models here. class Question(models.Model): q_id = models.CharField(max_length=10) category1 = models.CharField(max_length=100) category2 = models.CharField(max_length=100) descr = models.TextField() 4) registered my models in admin.py with the following from .models import Question admin.site.register(Question) from import_export import resources from core.models import Question class QuestionResource(resources.ModelResource): class Meta: model = Question but when i try to makemigrations the following error appears ModuleNotFoundError: No module named 'import_exportquestions' where is my mistake? -
django seems to have a leak of windows system handles
I've been practicing and learning Django. but i found that on my windows 7 64bit, when i run server, windows handles' number jump up by 2000 per second. very intimidating.(refer to my pic below) and then at the end , my laptop died with "insuffient recouses to complete service". I have to power off my laptop, even "shutdown" button can't work. running other python program works fine. I've been working on python for 2 years. django version = 1.11 , 3.0 I also tried, still the same. appreciate if you have some workaround. Danny windows handles 2000 added per a second when running django runserver -
How to display django success message in every template from one view?
Here I have one function for newsletter which will be used in every template in the project.The issue here is the success message is displaying only in the contact page template.I have placed django message tag {{message}} in the base.html only.It is working fine in the contact.html page.The corresponding message for contact and newsletter displays correctly in the contact_page template but not in other templates .Other templates also extends base.html like the contact.html. How can i display newsletter success message in every template.I don't want to write {{message}} in every template. Is there any solution for this ? views.py def contact(request): form = ContactForm() if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your message has been sent successfully.') return redirect('contact:contact_page') return render(request, 'contact/contact_page.html', {'form': form}) def newsletter(request): form = NewsletterForm() if request.method == "POST": form = NewsletterForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Thank you for your subscription.') return redirect(request.META['HTTP_REFERER']) return render(request, 'base.html', {'news_form': form}) -
ERROR : Target WSGI script not found or unable to stat
I use elasticbeanstalk and setting .ebextensitons/django.config as : option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config/wsgi.py aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings and also, wsgi.py is exist in config. I don't know why below error message appear. [Sun Feb 16 06:24:43.546754 2020] [:error] [pid 4688] [client ~~~ip~~~~~] Target WSGI script not found or unable to stat: /opt/python/current/app/config [Sun Feb 16 06:15:55.043332 2020] [:error] [pid 4575] [client ~~ip~~~~~] Target WSGI script not found or unable to stat: /opt/python/current/app/config, referer: ~~~~~aws RDS endpoint~~~~~~ -
django File "options.py", line 581, in get_field return self.fields_map[field_name] KeyError: 'user_email' error
I have not changed code of any file of django project. But when I execute python manage.py migrate I 'm getting error - ''' File "C:\Python37-32\lib\site-packages\django\db\models\options.py", line 581, in get_field return self.fields_map[field_name] KeyError: 'user_email' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Python37-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python37-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python37-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python37-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Python37-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Python37-32\lib\site-packages\django\core\management\commands\migrate.py", line 233, in handle fake_initial=fake_initial, File "C:\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Python37-32\lib\site-packages\django\db\migrations\executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "C:\Python37-32\lib\site-packages\django\db\migrations\migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Python37-32\lib\site-packages\django\db\migrations\operations\fields.py", line 249, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "C:\Python37-32\lib\site-packages\django\db\backends\sqlite3\schema.py", line 138, in alter_field super().alter_field(model, old_field, new_field, strict=strict) File "C:\Python37-32\lib\site-packages\django\db\backends\base\schema.py", line 537, in alter_field new_db_params = new_field.db_parameters(connection=self.connection) File "C:\Python37-32\lib\site-packages\django\db\models\fields\related.py", line 971, in db_parameters return {"type": self.db_type(connection), "check": self.db_check(connection)} File "C:\Python37-32\lib\site-packages\django\db\models\fields\related.py", line 968, in … -
how do i get values from multiple selected choice box in django
i am trying to get values from multple selected choice box the bellow attached screenshot make sense what i want,so when i select all these fields i want to save them in database,and want to display all selected fields value in django admin in same column with comma (,) separated, but the code bellow i write geting nothing from the fields except this one as square bracket'[]' django = 3.3 python = 3.7 image file models.py YourRoleInCompany = models.CharField(max_length=100,) views.py YourRoleInCompany = request.POST.getlist('YourRoleInCompany') signup.html <input type="checkbox" value="Investitor / Actionar" id="1" name="YourRoleInCompany"> <input type="checkbox" value="Manager General (CEO)" id="2" name="YourRoleInCompany" <input type="checkbox" value="Manager de Departament" id="3" name="YourRoleInCompany" <input type="checkbox" value="Lider de Echipa" id="4" name="YourRoleInCompany" -
How to set Permission for custome module in drf
I am trying to set permission from my custome module. Here is my model classes: class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) role = models.CharField(max_length=30, default='manager') status = models.IntegerField(default=1) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email Now I want to set permission based on role(such as manager,customer,admin etc) value from the Account class. I am using function based view in this project. So now How I can do this? -
Recieving error when use Process and works fine when use Thread in Django Python
I am developing a solution in Django 2.2 in which I need to save some objects for each request until user is connected. When I am using threading.Thread its works fine, but I want to use the terminate() method of multiprocessing.Process also. When I test the same code with Process then it raise extension that it cannot import some modules. Here are code samples for Thread and Process: Code with Thread users_resources[request] = [] users_resources[request].append(DriverHandlerDotMed(request)) Thread(target=users_resources[request][0].run_until_connected).start() Code with Process users_resources[request] = [] users_resources[request].append(DriverHandlerDotMed(request)) Process(target=users_resources[request][0].run_until_connected).start() Error Details Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) File "C:\Users\Faizan\source\repos\DjangoSearchMedEquip\src\DriverHandlerDotMed.py", line 1, in <module> from .DriverHandler import DriverHandler File "C:\Users\Faizan\source\repos\DjangoSearchMedEquip\src\DriverHandler.py", line 3, in <module> from .settings import BASE_DIR, users_resources File "C:\Users\Faizan\source\repos\DjangoSearchMedEquip\src\settings.py", line 118, in <module> from .DriverHandlerDotMed import DriverHandlerDotMed ImportError: cannot import name 'DriverHandlerDotMed' from 'src.DriverHandlerDotMed' (C:\Users\Faizan\source\repos\DjangoSearchMedEquip\src\DriverHandlerDotMed.py) -
Switch database based on login or company credentials django rest framework on the fly
I want to have multiple database containing all tables, data etc and when user enters company credential. The settings will change to that company db I am using rest framework. I am using dosier for login register but they are saving data in the same master database. Is it possible to do the same in django. but before that user needs to add company. One approach i can think of is If a separate api is created with flask or whatever how can we change db settings on the fly in django -
How to checked multiple checkbox over loop
In One Array I am getting array like : ['1','2','3','4','5','6'] And In another array i Am getting array like : ['1','6'] In template i am doing like : <div class="col-md-10"> {% if edit_data.features %} {% for feature in edit_data.feature %} {% for features in edit_data.features %} {% if feature.id == features.feature_id %} checked='checked' {%endif%} {%endfor%} <input type="checkbox" name="features" value={{feature.id}} {{checked}}> {{feature.name}}</option> {%endfor%} {%endif%} </div> After This i am getting Like: How Can i select the checkbox over the loop i am not able to create variable inside if condition. i am newbe please let me now how can i make checkbox to be selected [1]: https://i.stack.imgur.com/LzVV4.png -
django+celery+redis,app. Control. Inspect ()
Now I want to use the app. Control. Inspect () to collect the list of pending tasks, and the waiting time of task in the queue, don't know how to get and write the code, is there any relevant snippet that I can see ?Thanks. -
hello can you help me
i hava an error as Unable to create process using 'C:\Users\Mr.M\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver' i cant fint any solution -
Ckeditor convert images to html tags
I am using CKEditor with Django. I faced an issue. When I upload an image in the CKEditor image looks good in the editor. But when I save images are converted to HTML tags. How can I fix it? -
Django: Related Objects for Authenticated User
In Django we can create related models: class User(models.Model): pass class TaskSet(models.Model): user = models.ForeignKey(User, related_name='tasksets') title = models.Charfield() class Task(models.Model): user = models.ForeignKey(User, related_name='tasks') taskset = models.ForeignKey(TaskSet, related_name='tasks') Makes sense, I can call request.user.tasksets– but what's the correct way to get the tasks in the taskset? request.user.tasksets.first().tasks will return all of the tasks for the entire task set– but how can I get the tasks for that user only? -
Multiple web frameworks in single AWS instance?
This is an infrastructure design question. Is it better to: Run multiple web frameworks on a single AWS instance? Run each framework in separate AWS instances? Here are the web frameworks used: Backend: Django + PostgreSQL Frontend: NodeJS Forum: Ruby on Rails + PostgreSQL Option 1 pros: No need to worry about AWS instance type (just use a powerful one) Easy to maintain when everything is in one place, only 1 instance Option 2 pros: Better allocation of AWS resources depending on load (backend / frontend / forum). Easier to scale? I am not sure what's the better option. Would love to hear your experience and opinion on this. Thanks. -
Default migrate table name rename
Since my project would like to create all the table into an old database, It would be a problem if I use the default name from Django. Is there any way to rename all the table like the JPG below? -
Video dialog not rendering properly using summernote-django in django website
I am using summernote for rich text editing . It is working fine with text but during video uploading/Inserting video url, it is fixing the width and height during posting and during rendering it is not showing proper dialog, In my case video dialog 20% cuts . for example it sets the width 640px during posting and during rendering it is showing same 640px which is not good as per page design and page requirement less than 450px . So I mean to say that it is not response in video dialogs. Please anyone help me for that . I add an image please check it Thank you . -
How do I call a Python function with parameters from an HTML page (alongside Django)?
I'm in the process of writing a Django app, but I've hit a slight roadblock. You see, I have the backend return an HTML page, and that works just fine. What I am having trouble with though is going the other way around. I am trying to call a function on the backend once the user clicks a button. Now, I've already searched to see if anyone else has asked this question before, but all the posts that came up had a different scenario linked to them. All of them were for GET requests, but I need to be able to POST some data instead. Does anyone know how I can do this? -
Django Python save database blog posts to a zipfile?
I have a django blog and want to download a backup zipfile with all the entries. The blog post text content is stored in the database. I have written this code with the goal of trying to get the zipfile to save a bunch of .txt files in the main zip directory, but all this code does is outputs a single corrupted zip file. It cannot be unzipped but for some reason it can be opened in Word and it shows all of the blog post text mashed up. def download_backups(request): zip_filename = "test.zip" s = BytesIO() zf = zipfile.ZipFile(s, "w") blogposts = Blog.objects.all() for blogpost in blogposts: sio = StringIO() sio.write(blogpost.content) filename = blogpost.title + ".txt" zf.writestr(filename, sio.getvalue()) resp = HttpResponse(s.getvalue()) resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename return resp Any help is appreciated. -
chained event after dropdown option select
I want to add a column that will only be shown when I select some specific options from dropdown menu. I had written the dropdown menu part(in django template) and also retrieved the option value in the backend. I can create a field after submitting the form by using that value but I want to dynamically change the form. What I thought should be the process is, is to take the value from the dropdown and apply an if condition on its value. What I want to know is how can I dynamically take its value without submitting the form