Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Independent SQLAlchemy and Django projects integration
I have a project that implemets SQLAlchemy ORM for sending some information (stores in postgres database) to Telegram Bot. It takes randomly reports from DB and sends automatically on schedule. However, there are no explicit accesses to database and no indirect interfaces for interation with data there. Whenever I need change something or add, I'm using CLI. Now I want to develop website with Django (for studying purposes) and implement some features as adding and edititing information in database in order to send to Telegram Bot some fresh data. Are there any opportunities to keep Django web application separate from scheduled SQLAlchemy application? If I make some code changes in SQLAlchemy project DB, will they automatically migrate to Django ORM? Or after each changes in sqlalchemy I need to do python manage.py inspectdb > models.py? Do you know some solutions? I found several answers on the same issue: https://djangostars.com/blog/merging-django-orm-with-sqlalchemy-for-easier-data-analysis/ Configuring Django to use SQLAlchemy However, my main purpose is to use Django ORM for web application and SQLAlchemy for scheduled process. Solutions above can't help me -
How to connect Big Query with python using pyreportjasper
i am using the configuration as follow { 'driver': 'generic', 'jdbc_url': 'jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId={project_id};OAuthType=0;OAuthServiceAcctEmail={email};OAuthPvtKeyPath={path_to_p12_file};', 'jdbc_driver': 'com.simba.googlebigquery.jdbc.Driver', 'jdbc_dir': path_to_all_jdbc_jar_dir, } All the required jar files are in the path_to_all_jdbc_jar_dir I can successfully connect to Jasper studio using similar configuration and it works However i ended up getting this error `NameError: Error fill report: Erro fill internal: java.lang.ClassNotFoundException: com.simba.googlebigquery.jdbc.Driver Anyone know what could possibly wrong here. Thanks alot I am using the jdbc driver below from https://cloud.google.com/bigquery/docs/reference/odbc-jdbc-drivers SimbaJDBCDriverforGoogleBigQuery42_1.2.21.1025 -
Debugging Dockerized Django Project on local machine
I am fairly new in using Docker containers, I had been using Pycharm debugging mode for inspecting views behaviour on local machine, using virtual environments. Can someone guide me, about the standard procedure of adding a breakpoint and step by step inspection, of a Python Django project run inside docker containers(with different services like mongodb, redis and project's container itself. What I did: Run the project locally using Docker, looked into its logs. I am expecting to add breakpoints and check the code state at each step. I am trying to avoid replicating whole codebase in another directory and run it using virtual environment. -
DRF multi fields base match filter queryset
I'm creating a search functionality where we can search based of first_name, last_name, username.it should filter all matches( if at least anyone fields match it should consider ) users except login users. this is what I have done but I'm searching for an efficient Django queryset. if search_name is not None and len(search_name) >= 3: search_obj_1 = User.objects.filter(first_name__iexact=search_name).exists() search_obj_2 = User.objects.filter(last_name__iexact=search_name).exists() if search_obj_1: search_obj_1 = User.objects.filter(Q(first_name__iexact=search_name)) &User.objects.filter(~Q(id=logged_user_id)) search_obj_2 = User.objects.filter(Q(last_name__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj_3 = [] search_obj = list(chain(search_obj_1, search_obj_2, search_obj_3)) elif search_obj_2: search_obj_1 = [] search_obj_2 = User.objects.filter( Q(last_name__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj_3 = User.objects.filter( Q(username__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj = list( chain(search_obj_2, search_obj_3, search_obj_1)) else: search_obj_1 = [] search_obj_2 = [] search_obj_3 = User.objects.filter( Q(username__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj = list( chain(search_obj_3, search_obj_1, search_obj_2)) so is there any better way do the same thing. -
Foreign key filter in a child object
I have the models: Boss - Shop - Employee - WorkSpace class Boss(models.Model): fullname = models.TextField() class Shop(models.Model): name = models.TextField() address = models.TextField() phone = models.TextField() boss = models.ForeignKey( Boss, on_delete=models.CASCADE, related_name="shops" ) class Employee(models.Model): name = models.TextField() phone = models.TextField() shop = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name="employees" ) class WorkSpace(models.Model): name = models.TextField() employee = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name="work_spaces" ) I filtered with Boss.objects.filter(shops__employees__work_spaces__type=C1) and got: { "shops": [ { "id": 32, "name": "Garden flowers", "address": "5 st. Hool-Maa", "phone": "879124851861598", "employees": [ { "id": 150, "name": "Mike", "phone": "8154451246", "work_spaces": [ { "id": 497, "type": "B12" }, { "id": 15, "type": "Z5" }, { "id": 33, "type": "C1" } ] } ] } ] } But I only need C1 from work_spaces: [{ "id": 33, "type": "C1" }] How can I exclude other work_spaces from the queryset or do I need to convert the result to a list and then filter using a for loop? There can be many workspaces, and I don't need to show them all to the user, I need information about the Boss, the Shop, the Employee.. -
Django objects.all() can't work in aaPanel
If objects.all()[:1000000] it can work,but objects.all() it can not work,just retutn Nothing,no error I don't know what happen,it works fine on my computer Everyone can help me? it's my code def get_data(request): units=ErpWater168ShopCardset.objects.all() return render(request,"listall.html",locals()) I try use objects.filter() and objects.exclude(),they work normally,just objects.all() can't work -
Gather all logs from entire flow of celery's task
@shared_task() def run_scraper_task(): ImportDataTaskInfo = apps.get_model("data", "TaskInfo") logger = get_task_logger("A") logger.info("XXXXXXX") task = TaskInfo.objects.create(status=DataTaskStatuses.IN_PROGRESS) try: logger.info("XXXX") crawler_settings = Settings() crawler_settings.setmodule(setting1) crawler = CrawlerProcess(settings=crawler_settings) logger.info("XXXX") crawler.crawl(Spider) reactor.run() logger.info("XXXX") task.status = TaskStatuses.SUCCESS logger.info("XXXX") except Exception as error: logger.error("XXXXX") task.info += str(error) + "\n" task.status = TaskStatuses.ERROR finally: import_task.save() So i have scrapy connected to celery task, and scrapy execute spider.py and pipeline.py where i have for instance def process_item(self, item, spider): logger = get_task_logger("A") logger.info("Pipeline activated.") # i want this message to go into task.info. I want to inject all my logs into object task.info attribute. How i can catch it in spider and in pipeline? I have tried to catch proper task object for every step, but this seems not to be optimal option. -
Django admin: How can I put my logo on the page instead of the site title?
I created django project. It works fine and I can login to admin section of the site. At the top of every page, django shows the "django administration". I know how to change it. Now, I want to know how can I put my logo on the page instead of that title? I read about block branding but I am confused and some solutions I tried did not work. Of course maybe it was my fault and they detailed too advanced. I am newbie , so will be glad to receive more detailed solution. Thanks in advance. -
How to save image to model in wagtail?
When I try to do this I get the following error "'BoundField' object has no attribute 'width'". def serve(self, request): post_data = request.POST or None ... new_image = Image.objects.create( file=review_form['file'], title="Image title" ) new_review.image = new_image if new_review.is_valid(): new_review.save() My form class ReviewForm(TemplateForm): file = forms.ImageField() I used part of code of this answer from wagtail.images.models import Image def save(self, commit=False): if not commit: raise Exception("This form doesn't support save(commit=False)") # build the instance for this form, but don't save it to the db yet instance = super(MyForm, self).save(commit=False) # create the Image object avatar = Image.objects.create( file=self.cleaned_data['avatar_image'], title="Image title" # you may need to add more fields such as collection to make it a valid image... ) # attach the image to your final model, and save instance.avatar = avatar instance.save() return instance -
Data transfer for Jinja2 from Updateviev
I have such a template on every html page into which I want to transfer data from my url processors: {% block title %} {{ title }} {% endblock %} {% block username %} <b>{{username}}</b> {% endblock %} When using regular def functions, I pass them like this: data_ = { 'form': form, 'data': data, 'username': user_name, 'title': 'Add campaign page' } return render(request, 'dashboard/add_campaign.html', data_) But when I use a class based on UpdateView: class CampaignEditor(UpdateView): model = Campaigns template_name = 'dashboard/add_campaign.html' form_class = CampaignsForm There is a slightly different data structure, could you tell me how to pass the required date through the class? -
ValueError: could not convert string to float: '$2,464.34'
I am trying to convert the data to float in order make it as numerical format in excel to sort the data i am getting error.wherever the float in mentioned i did it now but previously there was no float . def get_output_value(self, key, value, neutral=None): display = value if value is None and not neutral.person.is_active: return '-', '-' if value is None: return float(f"${Decimal('.00')}"), float(f"${Decimal('.00')}") if isinstance(value, Decimal): return float(f"${intcomma(value.quantize(Decimal('.00')))}"), float(f"${intcomma(display.quantize(Decimal('.00')))}") return float(value), display -
How to accept variable as encoded/decoded format in django through the url?
I would like to pass a variable through url and sometimes I want to receive the url as it it. If the variable is in encoded format then I want to receive it as encoded format. I used the path("myurl/<slug:post_name>",post.post_details.as_view()), When I recieve post_name = %E5%B9%B4%E6%9C%AB%E8%AA%BF%E6%95%B4%E, this is automatically getting decoded and I am getting chinese/japanese character depending on the post_name. The problem is some of the post_name is stored in the encoded format and I want to receive the string as it is. How can I achieve this ? Thank you. I tried the path converters from here Like path("myurl/<slug:post_name>",post.post_details.as_view()), and path("myurl/<str:post_name>",post.post_details.as_view()), but None of this worked. -
How to keep django-q run on ubuntu nginx server
I use ubuntu with nginx & gunicorn and try to run django-q How can I keep django-q run when shutdown terminal please -
How to use the same ModelForm form different admin classes with different models
I'm trying to create a common form with a date range validation that will be used in 20 admin classes with different model So I'm creating this mixin for each of them to use class DateControllerMixin(): def get_queryset(self, request): qs = dateControlQuerySet(super().get_queryset(request), self.parameter_name, request) return qs def get_form(self, request, obj=None, change= None,**kwargs): print(self.parameter_name) if request.user.groups.filter(name='slaughterhouse_date_controlled').exists(): form = DateControlledForm form.model_class = self.model form.parameter_name = self.parameter_name return form return super().get_form(request, obj, change, **kwargs) And this is the form but I can't find a way to make the form without specifying the model class in the Meta or use class attributes class DateControlledForm(forms.ModelForm): def __init__( self, *args, **kwargs ): self._meta.model = self.model_class super(DateControlledForm, self).__init__(*args, **kwargs) class Meta: # model = self.model_class fields='__all__' widgets = { 'the_date': AdminDateWidget(), } def clean(self, **kwargs): print(self.paramter_name) date = self.cleaned_data.get('the_date') today = datetime.today().date() days_limit = AppConfigurations.objects.get(parameter_name=self.parameter_name).parameter_value first_day = today - timedelta(days = int(days_limit)) if date < first_day: raise forms.ValidationError({ 'the_date': [_(f"Date cannot be before {first_day}.")]}) return self.cleaned_data I tried to edit the meta options from the init method but it didn't work -
django project not executing makemigrations command as expected in vscode editör
I have a django project. I moved my project from pyCharm editor to vscode editor. When I run the python manage.py makemigrations command, it creates a migration file for some applications under venv. I think it depends on the LANGUAGE_CODE value in settings.py but I used gettext_lazy in all my models. Even if I type the command python manage.py makemigrations app_label, it still creates migration files for projects under venv. The libraries installed with pip install under venv are my own django projects. I have always used gettext_lazy in these projects. Same projects execute makemigrations in pyCharm editor with no issues -
how do I put the oversized logo overlap the nav?
thanks for your help. I just starting to learn HTML and CSS. I have been wrestling with this oversize logo problem for a week now. How do I put the logo overlap the nav like a layer look? my html file: <nav class = "navigation-bar"> <link rel="stylesheet" href="{% static 'financeapp/style1.css' %}"> <img class = "logo" src ="{% static 'financeapp/family examiner 2.png' %}" alt="company logo" height = 150px width = 150px> <div class = "navigation-container"> <ul> <li><a href="#"> Home </a></li> <li><a href="#"> About </a></li> <li><a href="#"> Contact </a></li> <li><a href="#"> Join Us </a></li> </ul> </div> my css file: .navigation-bar { display:flex; margin: 0; padding: 0; align-items: center; text-align: center; } .logo { float: left; } .navigation-container { display: flex; justify-content: space-betwee; width: 100%; /*left side*/ } .navigation-container ul { margin: 0; padding: 0; width: 100%; /*right side*/ height: 70px; background-color: yellow; } .navigation-container li { display: inline; } .navigation-container a { padding: 10px; text-decoration: none; } thanks for your time. -
Using ORM and migrations in Django
I have good knowledge of databases (DML, DDL, PL/SQL) and would like to create a web app using the Django framework. I really like the idea of migrations and ORM in general. On the other hand, I feel overwhelmed with all the features of models and ORM querying and I'm not too fond of the idea of spending hours reading docs when I can do it with SQL in an instance. I can create tables and constraints using SQL scripts and then map them to the model using Meta options "table_name" and "managed". I assume that using ORM for simple selects, inserts, deletes and updates is perfect, but what about complicated joins? What is your opinion on this matter? Should I learn ORM, go the plain SQL way, or combine both somehow? -
how to solve error 'Command errored out with exit status 1'
I want to pip install the Django project's requirements.txt file, but I get this error during execution : ERROR: Command errored out with exit status 1: command: '/home/nikafarin-ai/MrMr/Projects/NEWS reader/git/news_reader/vir/bin/python3' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-eepbf4_k/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-eepbf4_k/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-eepbf4_k/mysqlclient/pip-egg-info cwd: /tmp/pip-install-eepbf4_k/mysqlclient/ Complete output (15 lines): /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-eepbf4_k/mysqlclient/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-eepbf4_k/mysqlclient/setup_posix.py", line 70, in get_config libs = mysql_config("libs") File "/tmp/pip-install-eepbf4_k/mysqlclient/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found mysql_config --version mariadb_config --version mysql_config --libs ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I set vs code to global mode and it recognized the modules in the requirements.txt file (except for two items) -
Excel data not sorting the type Decimal
I have a view where i export data the numerical data but when i sort the data it is not getting sorted as the excel is not considering the values as numerical data how can i convert them to numerical data in order to display the data in numerical format and make the sorting work.i have a function which gets the data here is how it looks. def get_output_value(self, key, value, neutral=None): display = value if value is None and not user.is_active: return '-', '-' if value is None: return f"${Decimal('.00')}", f"${Decimal('.00')}" if isinstance(value, Decimal): return f"${intcomma(value.quantize(Decimal('.00')))}",f"${intcomma(display.quantize(Decimal('.00')))}" return value, display -
attaching a csv file django
Hi i have generated a csv and it saves correctly in my media dir . This is how I generate the csv file : def export_to_csv_file(data, titles, file_name): csv_file_address = os.path.join(settings.MEDIA_ROOT, file_name) response = HttpResponse(content_type="text/csv") response["Content-Disposition"] = "attachment; filename={}".format(file_name) response.write("\ufeff".encode("utf8")) with open(csv_file_address, "w+") as file: writer = csv.DictWriter(file, fieldnames=titles, extrasaction="ignore") headers = {title: _(title).replace("_", " ").title() for title in titles} writer.writerow(headers) for row in data: writer.writerow(row) return response, file and this is how I use this function : data_file = export_to_csv_file( serializer.data, list(self.get_serializer().Meta.headers), file_name, ) email_html_message = render_to_string( "myhtml.html", {"host": settings.SITE_URL, "file_url": data_file[1].name}, ) email = EmailMessage( email_title, email_html_message, settings.EMAIL_FROM, ["mont@gmail.com"], ) with open(data_file[1].name, "r") as file: email.attach("attach_file", file.read(), "text/csv") email.send() when I pdb the file I find out the file type is <_io.TextIOWrapper name='D:\\02_work\\Golf\\media\\spender_liste_1669015631.216596.csv' mode='r' encoding='cp1252'> what should I do to send this csv file as an attached file? Also I have tested the with open(data_file[1].name, "w+") as file: email.attach("attach_file", file.read(), "text/csv") email.send() but this time get IndexError: list index out of range in the email.send() line -
Channels development server does not taking over my Django development server
I'm learning django(4.1) channels(4.0.0) from a YouTube video and now trying to configure ASGi. Using windows and gitbash. After configuration when I run server, instead of showing: Starting ASGI/Channels version 4.0.0 development server at http://127.0.0.1:8000 it simply shows: Starting development server at http://127.0.0.1:8000/ which instructor says it means "Channels development server does not taking over my Django development server as it should." We literally just made a project(mywebsite) and an app(chat), added channels and the app to setting, and in settings we added ASGI_APPLICATION = 'mywebsite.asgi.application' asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mywebsite.settings') application = ProtocolTypeRouter({ 'http': get_asgi_application(), }) I have compared my code to his from the source code he provided and nothing in different. Do I have a problem from my computer settings? -
How can i allow both IP Address and URL in django field?
I want to allow both flutterdemo.hp.com and 12.135.720.12 in django field. This is what i tried. from rest_framework import serializers, viewsets from django.core.validators import URLValidator class FlutterSerializer(serializers.HyperlinkedModelSerializer): fqdn_ip = serializers.CharField(max_length = 100, validators =[URLValidator]) But it is allowing all the text and just working as CharFiled. URLField is treating "flutterdemo.hp.com" as invalid. How can i achieve this? Thanks, -
Django : Custom AdminEmailHandler resulting error when starting the server (ValueError: The translation infrastructure cannot be initialized befo ...)
So i just defined a new class inside myproject/products/helpers.py that extends the django's AdminEmailHandler class (because i want to modify it to only send to specific emails / not all of the admins). class EbookTeamEmailHandler(AdminEmailHandler): def __init__(self, include_html=False, email_backend=None): AdminEmailHandler.__init__(self) self.include_html = include_html self.email_backend = email_backend def send_mail(self, subject, message, *args, **kwargs): self.mail_team_ebook(subject, message, *args, connection=self.connection(), **kwargs) def mail_team_ebook(subject, message, fail_silently=False, connection=None, html_message=None): """List email milik member team ebook""" recipients = [ "xyz@email.com" ] mail = EmailMultiAlternatives( '%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject), message, settings.SERVER_EMAIL, to=recipients, connection=connection, ) if html_message: mail.attach_alternative(html_message, 'text/html') mail.send(fail_silently=fail_silently) and defined the handler in my settings.py: LOGGING = { 'handlers': { ... 'mail_ebook_teams': { 'level': 'ERROR', 'class': 'products.helpers.EbookTeamEmailHandler' } ... }, 'loggers': { ... 'queue_create_product_error':{ 'handlers': ['queue_mailed','console','mail_ebook_teams'], 'level': 'DEBUG' }, ... } } the problem is when i start the server, it gives me error such : Unhandled exception in thread started by <function check_errors..wrapper at 0x7f3d788da170> Traceback (most recent call last): File "/home/dyaksa/.pyenv/versions/3.6.15/lib/python3.6/logging/config.py", line 390, in resolve found = getattr(found, frag) AttributeError: module 'products' has no attribute 'helpers' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dyaksa/Code/gm-core-api/venv/lib/python3.6/site-packages/django/utils/translation/trans_real.py", line 168, in _add_installed_apps_translations app_configs = reversed(list(apps.get_app_configs())) File "/home/dyaksa/Code/gm-core-api/venv/lib/python3.6/site-packages/django/apps/registry.py", line 138, in get_app_configs … -
Django materializecss datatable jquery
I am trying getting Uncaught ReferenceError: jQuery is not defined and Uncaught ReferenceError: $ is not defined while trying to load a Select2 dropdown with datepicker. I am using Materializecss, Datatables and jQuery with Django. How can I properly structure the base.html to ensure all required css, javascript and jquery is loaded only once? Below is my code for base.html, topsearchbar.html and dashboard.html (which is throwing the above errors) base.html <!DOCTYPE html> {% load static %} <html> <head> <!--Import Google Icon Font--> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet"> <link href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <!--Let browser know website is optimized for mobile--> <meta content="width=device-width, initial-scale=1.0" name="viewport"/> <link href="{% static 'css/dashboard.css' %}" rel="stylesheet"> <title>Title</title> </head> <body> {% include 'partials/sidenav.html' %} {% include 'partials/navbar.html' %} {% block content %} {% endblock %} <!--<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>--> <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"> </script> <script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js" type="text/javascript"> </script> <script> $('.button-collapse').sideNav({ menuWidth: 300, // Default is 240 edge: 'left', // Choose the horizontal origin closeOnClick: true // Closes side-nav on <a> clicks, useful for Angular/Meteor } ); // Show sideNav //$('.button-collapse').sideNav('show'); </script> <script> (function(window, document, undefined) { var factory = function($, DataTable) { "use strict"; $('.search-toggle').click(function() { if ($('.hiddensearch').css('display') == 'none') $('.hiddensearch').slideDown(); … -
set ImageField "upload_to" field of a Product based on their Category name - Django
class Product(models.Model): category=models.ForeignKey(Category, on_delete=models.CASCADE, related_name='product_category', to_field='category_name') name=models.CharField(max_length=255,) description=models.CharField(max_length=255) *************************************************** images=models.ImageField(upload_to='products/'+str(category.category_name), blank=True,null=True) *************************************************** price=models.DecimalField(decimal_places=2,max_digits=7) discount=models.DecimalField(decimal_places=2,max_digits=3, validators=[MinValueValidator(0),MaxValueValidator(0.99)]) def __str__(self): return self.name I want to save images relative to the category name and product name, therefore all products with the same name would be saved in the same file. I don't know if this is the best practice, so please if it shouldn't be like this specify the best way and how can I achieve what I want.