Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /invoicing/search/
In my localhost i have this error when i search something, for exemple number of invoicing, and at Web site server i have "Server Error (500)", for the same problem, can you help me to fixed this . enter image description here We have the supplier and the invoice, each supplier have 1 and more invoice, whem i go search the supplier for invoicing, i have this error "NoReverseMatch at /invoicing/search/ Reverse for 'profilePage' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['accounts/profile/(?P[0-9]+)$']" -
Unable to get current user inside django rest serializer
I'm unable to get current user inside serializer. I have passed context but still i get error like "user": [ "This field is required." ] #Serializer.py class AddressSerializer(ModelSerializer): class Meta: model = Address fields = "__all__" def create(self, validated_data): request = self.context["request"] validated_data["user"] = request.user return super().create(validated_data) #Views.py class AddAddress(APIView): permission_classes = [IsAuthenticated] def post(self, request): print(request.user) serializer = AddressSerializer(data=request.data, context={"request":request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, 200) return Response(serializer.errors) #Models.py class Address(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) full_name = models.CharField(max_length=35) email = models.EmailField(max_length=100) phone = models.BigIntegerField() address_line_1 = models.TextField(max_length=500) address_line_2 = models.TextField(max_length=500) zip_code = models.IntegerField() city = models.CharField(max_length=20) state = models.CharField(max_length=15) country = models.CharField(max_length=15) class Meta: verbose_name_plural = "Address" def __str__(self): return self.full_name I exactly don't know the problem behind this -
Django - set timezone in a django-admin command
I have a django-admin command which is handling message sending to different users in different countries. Each user should get the message at the same date - according to their local timezone. For example: a user in Paris should get a message every Monday at 10 am (Paris time), and a user in NY should get a message every Monday at 10 am (NY time). What happens is that they both get the message at Monday 10 am GMT. I can't use the user's browser local timezone, because its a script running independently in my server. Instead, I want to send the message according to a TZ stored in my DB for each users preferences. How can I send the message according to each user's TZ in my "handle" function? I was trying to use the "django.utils.timezone.activate" but I am not really sure how to make it work -
Chained task or dependent task using celery and django
I am using celery for scheduled task management in my django app. using "app.conf.beat_schedule" i can schedule task successfully. But one of my task depends on another scheduled task and accepts params returend from it. In that case I am facing problem, seracing through internet I became confused and nothing found workable for me. I tried the following and it shows: " Scheduler: Sending due task chained (celery_task_1)" Inside celery.py import os from celery import Celery, group os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'chained': { 'task': 'celery_task_1', 'schedule': 5.0, 'args': (), 'options': { 'queue': 'default', 'link': signature( 'celery_task_2', args=(), kwargs={}, queue='default' ) } } } -
Add minimal parameters to logs including user ip address, user ID and time(in django)
Can anyone guide me in this? Add minimal parameters to logs including user ip address, user ID and time (in Django) -
Permission Denied for nginx django deployement on aws nginx (13: Permission denied)
I have the same issue. When i run the (sudo -u www-data stat /home) it gives error. you don`t have permission to execute this command. Although i have given the admin privileges from root user. -
How can i validate django field with either of two validators?
Here is the code, I want ip_address to satisfy either of validate_fqdn or validate_ipv4_address. import re def validate_fqdn(value): pattern = re.compile(r'^[a-zA-Z0-9-_]+\.?[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$') if not pattern.match(value): raise ValidationError('Provided fqdn is not valid') return value class KSerializer(serializers.HyperlinkedModelSerializer): ip_address = serializers.CharField(max_length = 100, validators = [validate_fqdn, validate_ipv4_address]) How can i achieve this? Thanks, -
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)