Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
in django:db.sqlite3>>json file>>mysql_db,UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } ---------- DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysite_db', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '3306', 'TEST': {'CHARSET': 'utf8', }, } } File "C:\blog_env\lib\site-packages\django\core\management\commands\loaddata.py", line 113, in loaddata self.load_label(fixture_label) File "C:\blog_env\lib\site-packages\django\core\management\commands\loaddata.py", line 168, in load_label for obj in objects: File "C:\blog_env\lib\site-packages\django\core\serializers\json.py", line 66, in Deserializer stream_or_string = stream_or_string.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte (blog_env) PS C:\blog_env\mysite> create database: create database mysite_db default charset=utf8mb4 default collate utf8mb4_unicode_ci; in db_sqlite3: python manage.py dumpdata > data.json input mysql: python manage.py loaddata data.json -
django-ckeditor doesn't show up on grappelli admin in Django
I'm trying to use ckeditor on grappelli admin in Django. In local environment, it's working very well and it shows up well. However, after deploying it into production environment. The editor doesn't show up. Like you see image below, it's just blank and nothing. settings.py DJANGO_APPS = [ ... 'ckeditor', 'ckeditor_uploader' ] CKEDITOR_UPLOAD_PATH = "ckeditor_uploads/" CKEDITOR_CONFIGS = { 'default': { 'toolbar': [["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Subscript", "Superscript"], ['Undo', 'Redo'], ["Source"], ["Maximize"]], }, } STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') These are all settings for ckeditor in my Django app. Does anyone know why it's happening? -
How to do a inner join to get only the values saved on the table
How can I get only the law saved from an specific user in marked table? When a user register a law, the usuer id (user_id) and the law id (law_id) is saved in marked table. How can I get only the laws register by the user and order by law updated_at field ? My model: class Law(models.Model): name = models.CharField('Nome', max_length=100) description = models.TextField('Descrição', blank = True, null=True) updated_at = models.DateTimeField( 'Updated at', auto_now=True ) class Marked(models.Model): law = models.ForeignKey(Law, on_delete=models.CASCADE, verbose_name='Lei', related_name='marcacaoArtigos') user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='markedUser', related_name='markedUser') -
Can't Run Django Manage.py from Venv
I'm trying to run manage.py makemigrations for my django app, and I'm getting a "Couldn't import Django" message. I know how venv works and I'm sure my environment includes Django. See below; I try to run manage.py (running into the error), and then I run $ django-admin --version, and it shows the version of Django. (venv) emmett@emmett-HP:~/PycharmProjects/onramp_crm$ sudo python manage.py makemigrations contacts Traceback (most recent call last): File "manage.py", line 18, in <module> "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? (venv) emmett@emmett-HP:~/PycharmProjects/onramp_crm$ django-admin --version 2.0.9 (venv) emmett@emmett-HP:~/PycharmProjects/onramp_crm$ This is a django-cookiecutter project using Pycharm Pro edition. I've deleted the onramp_crm/venv folder and completely reinstalled the venv, setting up a new interpreter in Pycharm as well. Logged out & restarted Ubuntu, restarted Pycharm, everything I can think of. -
IOError - [Errno 102] Operation Not Supported On Socket
I am trying to deploy a app via Elastics Beanstalk AWS & Django however, when its starts creating the app version I get the message IOError - [Errno 102] Operation not supported on socket './Library/Application Support/Code/1.29.1-shared.sock' Not sure exactly how to resolve this error, as I specified all default settings and I have not customise anything yet. Do I need to change to the socket alternative? If so how can I do this? -
how to get product_id values from Get table and pass them to Lang table
how to get product_id values from Get table: res1 = models.Get.objects.filter(order_id=Order_id).values('product_id') res = models.Lang.objects.filter(id_product__in=res1) -
when saving form I need it to save and continue on the same page
I need to save the form, it stays on the same page with the updated form that was saved that does not go to core_list_movrotative but stays in 'core / update_movrotativos.html' @login_required def movrotativos_update(request, id): data = {} mov_rotativo = MovRotativo.objects.get(id=id) form = MovRotativoForm(request.POST or None, instance=mov_rotativo) data['mov_rotativo'] = mov_rotativo data['form'] = form if request.method == 'POST': if form.is_valid(): form.save() return redirect('core_lista_movrotativos') else: return render(request, 'core/update_movrotativos.html', data) -
How to I prevent Django Admin for overriding the custom widget for a custom field?
I have a model field, a form field, and a widget that I am using in an app. The details of the code don't matter. The key is that the field correctly renders in regular forms but is overridden in admin. Here is some pseudo-code of what the field basically looks like: class SandwichWidget(forms.Widget): template_name = 'sandwichfield/widgets/sandwichfield.html' def __init__(self, attrs=None, date_format=None, time_format=None): widgets = ( NumberInput(), Select(choices=FILLING_CHOICES), NumberInput(), ) super(SandwichWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: value = Sandwich(value) return [ value.top, value.middle, value.bottom ] return [None, None, None] class SandwichFormField(forms.MultiValueField): widget = SandwichWidget def __init__(self, input_date_formats=None, input_time_formats=None, *args, **kwargs): fields = ( forms.IntegerField(), forms.CharField(), forms.IntegerField(), ) super(SandwichFormField, self).__init__(fields, *args, **kwargs) class SandwichField(models.PositiveIntegerField): def get_internal_type(self): return 'IntegerField' def formfield(self, *args, **kwargs): defaults={'form_class': SandwichFormField} defaults.update(kwargs) return super(SandwichField, self).formfield(*args, **defaults) It apparently happens because of this line in django/contrib/admin/options.py which specifies the override of the models.IntegerField should be widgets.AdminIntegerFieldWidget. Because models.PositiveIntegerField inherits from models.IntegerField, and because line 181 loops over all subclasses of the field, it seems like there is no way to prevent the widget from being overridden in admin. This is a real problem, because I use this custom field, with its custom widget, all over my site and … -
why 'pip install mysqlclient' not working in ubuntu 18.04 LTS
I have just created a virtual environment on my machine (I am running on ubuntu 18.04 LTS). I have the python version of 3.6.7 and now I want to install mysqlclient into my virtual environment. After I do 'pip install mysqlclient' it didnt work, instead it gave me errors saying 'Command "python.py egg_info" failed with error code 1 in /tmp/pip-install-zd21vfb3/mysqlclient/', and that the msql_config file is not found. My setup tools are all up to date. Any help. -
best python web framework for bloging
So I've been confused lately about python web frameworks. I want to build a blog to publish new posts every day something like a news website I've been working with Django and I know it doesn't have this capability built-in I've also tried Django CMS which can build pages easily but can't show all the pages like posts in a blog in the home page (or I have not found it yet) my Question is should I switch to another framework for what I want or Django CMS is OK? -
How to uniquely identify the same user across multiple HTTP requests in Django?
I am working on a Kerberos backend for social-django and with Kerberos we need to perform a handshake process. The trouble with the social-auth framework is that my backend class is instantiated several times so I need to be able to keep track of which user (aka which browser) the request is coming from so that I can continue the handshake where it left off. Essentially I want to know how I can implement a stateful protocol over stateless transport like HTTP. -
Lost connection to Mysql Server during query i try a lot of solutions but not working
i had successfully installed python and django and i am trying to migrate djanto to WAMP Mysql server and i had tried a lot of solutions Like increase the maximum allowed packet of Mysql and the connection timeout to 6000 but all of these things doesn't work !! Here is the image of mysql Settings and i have this code in the init.py import pymysql pymysql.install_as_MySQLdb() -
How to enter the Django shell in read-only mode?
I'm interested in using a form of the Django shell which only permits read operations. So far, I've read this blog article (https://chase-seibert.github.io/blog/2012/12/21/read-only-django-shell.html), which seems to be based on setting django.db.router.db_for_write to None. Is this the recommended way to do this? As I understand from https://docs.djangoproject.com/en/2.1/topics/db/multi-db/#using-routers, the django.db.router is the 'master router' and it is not clear to me whether I can modify its attributes without affecting the environment in which the database is running. Perhaps there is another way, like creating a database (in my case, MySQL) user with only read permission, and starting a Django shell connected as that user? -
Creating a custom django logging handler. 'module' object has no attribute 'Handler'
I'm attempting to create a class based logging handler which notifies some third party service when the app sees a DisallowedHost exception using some of the built in logging configurations provided by django. However, I'm getting a particular import error that I am unable to understand how to resolve. My settings.py LOGGING = { ... 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'notify_my_service': { 'level': 'ERROR', 'class': 'tools.exception_logging.NotifyMyServiceHandler' } }, 'loggers': { ... 'django.security.DisallowedHost': { 'handlers': ['notify_my_service'], 'propagate': False, }, }, } My exception handler: import logging class NotifyAirbrakeHandler(logging.Handler): def emit(self, error): doSomething() The big traceback Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/dist-packages/django/utils/log.py", line 75, in configure_logging logging_config_func(logging_settings) File "/usr/lib/python2.7/logging/config.py", line 794, in dictConfig dictConfigClass(config).configure() File "/usr/lib/python2.7/logging/config.py", line 576, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'notify_my_service': 'module' object has no attribute 'Handler' So, it appears the logging module for some reason isn't getting properly imported. I've tried examples from other threads such as importing settings in the … -
change serializer to show both id and title of a foreignKey field
I'm using DRF and I have a Profile serializer with a group field that is a foreignKey to Group model. Profile Serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('group', ...) Profile Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # other fields group = models.ForeignKey(Group, on_delete=models.CASCADE) Group Model: class Group(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title Group Serializer: class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('title', 'id') extra_kwargs = {'id': {'read_only': True}} I have a route in my SPA that showing a list of profiles. I want to show the group title for each profile but this serializer only provide me an id of group and I don't want to create another view to get id of group and give me title. so I search about it and it was 2 solution first StringRelatedFieldthat is read_only and SlugRelatedField. I changed ProfileSerializer and add SlugRelatedField like this: class ProfileForAdminSerializer(serializers.ModelSerializer): group = serializers.SlugRelatedField( many=False, queryset=Group.objects.all(), slug_field='title' ) class Meta: model = Profile fields = ('group', ...) now I have access to title of profile group but the problem is I have to create Profile with providing title of group field, but I want to create Profile like … -
Setting Django and Apache on Justhost Server Centos 6.10
My organization has a Justhost dedicated server account that runs on CentOS 6.10. The Justhost subscription runs until 2021, and it uses cpanel. The problem is that my organization want to move from Joomla to Django based web app. I have successfully installed Django that runs on virtualenv. Now, I need to install and configure apache and mod_wgsi and set Up Apache Virtual Hosts on CentOS 6 to run the domain off of an IP address. Any guide on how to do this without cpanel will be appreciated. -
Django RQ rqworker freezes indefinitely
This week, my integration tests stopped working. I figured out that it was a django-rq job that just stuck indefinitely. My output: $: RQ worker 'rq:worker:47e0aaf280be.13' started, version 0.12.0 $: *** Listening on default... $: Cleaning registries for queue: default $: default: myapp.engine.rules.process_event(<myapp.engine.event.Event object at 0x7f34f1ce50f0>) (a1e66a46-1a9d-4f52-be6f-6f4529dd2480) And that's the point at which it freezes. I have to keyboard interrupt The code has not changed. To be certain, I went back to the master branch, checked it out, re-ran integration tests, and they, too fail. How can I start to debug redis or rq to understand what might be happening? Is there a way to view the actual queue record? -
Django Send Email with forbidden access permission
I am now using Django as the backend API endpoints and I want to send out email to for notification. settings.py #Email settings EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_PASSWORD = 'test.' EMAIL_HOST_USER = 'test@gmail.com' EMAIL_PORT = 587 views.py def GetEmailNotification(request): subject = "This is a test email" message = "This is a test message" from_email = 'test@gmail.com' send_mail(subject, message, from_email, ['test@gmail.com'], fail_silently=False) return HttpResponse("sent!") urls.py urlpatterns = [path('emailNotification/', GetEmailNotification)] But when I did the get request. it gave the error OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions How to solve this issue? Any ideas? -
Django foreignkey field filtering problem
I´m trying to filter a queryset with a ForeignKey field but I get the following error: Cannot resolve keyword 'workflowcontenidos' into field. Choices are: categoria_producto, descripcion_brief, descripcion_long, estatus_contenido, estatus_contenido_id, foto_1, foto_2, id, perfil_cliente, productosbase, usos, video My models are: class WorkflowContenidos(models.Model): estatus = models.CharField(max_length=200, help_text="Estatus de contenido", blank=False, null=True) def __str__(self): return str(self.estatus) class Categorias_Producto(models.Model): categoria_producto = models.CharField(max_length=50, help_text="Catergoría de producto", unique=True, blank=False, null=True) descripcion_brief = models.TextField(max_length=200, help_text="Descripción resumida", blank=True, null=True) descripcion_long = models.TextField(max_length=500, help_text="Descripción extendida", blank=True) usos = models.CharField(max_length=200, help_text="Usos (separados por comas)", blank=True, null=True) foto_2 = models.ImageField(upload_to='', default="", blank=False, null=False) foto_1 = models.ImageField(upload_to='', default="", blank=False, null=False) video = models.URLField("Link brand video", max_length=128, blank=True, null=True) perfil_cliente = models.CharField(max_length=200, help_text="Perfil de cliente", blank=True, null=True) estatus_contenido = models.ForeignKey("WorkflowContenidos", help_text="Estatus del contenido", blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return str(self.categoria_producto) The "estatus" values in the WorkflowContenidos model are: Incompleto Revisión Aprobado The view: def WorkflowContenidosView(request): lista_visualizacion = Categorias_Producto.objects.filter(workflowcontenidos__estatus='Incompleto') return render(request, 'catalog/content-workflow.html', { 'lista_visualizacion': lista_visualizacion }) -
Access Atrributes of a model
I have built a model for a user using the OnetoOneField(User). I have also added another field called keys. class AppUser(models.Model): user = models.OneToOneField(User) key = models.CharField(max_length= 32, default="") def __str__(self): return self.user.username Now after logging in using a particular username, how do I access the key attribute for that username in views.py file ? -
Django: python3 manage.py migrate ModuleNotFoundError: No module named 'django'
i'm a total noob in django so go easy on me.. i tried to run these commands on ubuntu terminal and gave me the same error python3 manage.py migrate python manage.py makemigrations MyAppName python manage.py migrate python manage.py syncdb --all error message: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? and i was told that i should never edit manage.py -
Systems decelopment: class diagram
Is it possible to have more than one association class in one association? -
How can I create a single csv file with data and fields from two different tables using python?
I am trying to get data from from two different tables and converting them into a single csv file. The scenario is that table1 have a key that refers to the data in table2 and I want to replace the value in table1 with the corresponding value from table2 and convert the final result into a csv file. -
Django: Math on Models
I need to do some math against a value and I'm very confused about F(). I've read through the docs and searched for examples but I'm missing some fundamentals. Could you help with a solution and give some pointers about how to make sense of this? My attempts below are commented out. I'm just trying to convert Mb to GB. If I could get a 2 decimal value that would be be really wonderful. class DatastoreInfo(models.Model): [ ... ] total_capacity = models.IntegerField(db_column='Total_Capacity', blank=True, null=True) [ ... ] class Meta: managed = False db_table = 'Datastore_Info' def ecsdatastores(request): form = myForm() results = {} if request.method == 'POST': if 'listxyz' in request.POST: form = myForm(request.POST) taf = form['taf'].value() results = DatastoreInfo.objects.filter(f_hostname=c_name) # results = DatastoreInfo.objects.filter(f_hostname=c_name, total_capacity=F('total_capacity') / 1000) # results = DatastoreInfo.objects.update(total_capacity=F('total_capacity') / 1000).filter(f_hostname=c_name) return render(request, 'dpre/datastoreinfo.html', {'form': form , 'results': results}) -
'Main process exited' error Gunicorn systemd file
I follow this article to deploy my Django project. I created gunicorn.service file in /etc/systemd/system/gunicorn.service with this configuration: [Unit] Description=gunicorn daemon After=network.target [Service] User=azizbek Group=www-data WorkingDirectory=/home/admin/respositories/ninersComingSoon ExecStart=/root/.local/share/virtualenvs/ninersComingSoon-_UZsUc5R/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/admin/repositories/ninersComingSoon/niners.sock ninersComingSoon.wsgi:application [Install] WantedBy=multi-user.target Location of my project is /home/admin/respositories/ninersComingSoon And when I run systemctl start gunicorn systemctl enable gunicorn it must create niners.sock file inside the project directory but it doesn't. Then I typed this command to figure out what I did wrong. journalctl -u gunicorn And the result was Dec 05 02:05:26 server.niners.uz systemd[1]: Started gunicorn daemon. Dec 05 02:05:26 server.niners.uz systemd[1]: gunicorn.service: Main process exited, code=exited, status=203/EXEC Dec 05 02:05:26 server.niners.uz systemd[1]: gunicorn.service: Unit entered failed state. Dec 05 02:05:26 server.niners.uz systemd[1]: gunicorn.service: Failed with result 'exit-code'. So can you help me to solve this problem?