Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix IntegrityError 1048 in django
So, i just made a upload feature to insert data into databases. Data inserted successfully into the database but show an error messages Before, i tried to change the column name on my excel .. i thought it was the problem, but after i undo the changes to default .. error still happened. Here's my view code Views.py if 'uploaddatasiswa' in request.POST: dataset = Dataset() new_siswa = request.FILES['uploadSiswa'] if not new_siswa.name.endswith('xlsx'): messages.info(request, 'Format tidak valid!') else: imported_data = dataset.load(new_siswa.read(),format='xlsx') for data in imported_data: tambah_siswa = modelUser( username = data[0], namadepan = data[1], namabelakang = data[2], password = data[3], email = data[4], jeniskelamin = data[5], tanggallahir = data[6], agama = data[7], alamat = data[8], telepon = data[9], role = "siswa" ) tambah_siswa.save() return HttpResponseRedirect("/admin/daftarsiswa") return render(request,'tambahsiswa.html') Models.py class modelUser(models.Model): namadepan = models.CharField(max_length=200, null=False, blank=False) namabelakang = models.CharField(max_length=200, null=False, blank=False) username = models.CharField(max_length=200, null=False, blank=False) password = models.CharField(max_length=200, null=False, blank=False) email = models.CharField(max_length=200, null=False, blank=False) jeniskelamin = models.CharField(max_length=200, null=False, blank=False) tanggallahir = models.DateField() agama = models.CharField(max_length=200, null=False, blank=False) alamat = models.CharField(max_length=200, null=False, blank=False) telepon = models.CharField(max_length=200, null=False, blank=False) jumlahkelas = models.CharField(max_length=200, null=True, blank=True, default=0) role = models.CharField(max_length=200, null=False, blank=False) def __str__(self): return self.username Tables -
How can I get value from one function in another function in Django, views()
Hello I am new to Django I want to get latitude and longitude from myview1 function to myview function so that I can Post that values and put into the relevant code. PLease Can anyone guide me regarding this? def my_view1(request): latitude='latitude' longitude='longitude' context = {'latitude':latitude, 'longitude':longitude} my_view(context) return (context) @csrf_exempt @require_http_methods(["POST"]) def my_view(request,context): if request.method == "POST": # value_data=(my_view1(data=request.POST)) value_data=my_view1().objects.all() latitude = request.POST.get(value_data['latitude']) longitude = request.POST.get(value_data['longitude']) # In this example I am reading a file with (time, x, y) as dimensions xarr = xr.open_rasterio('/home/shaheer07/New Rasters/image_factors.tif') # Slice one of the bands img = xarr[0, :, :] #Use the .sel() method to retrieve the value of the nearest cell close to your POI pixel_value = img.sel(x=latitude, y=longitude, method="nearest") image = '/home/shaheer07/New Rasters/image_factors.tif' with rasterio.open(image) as f: # Load metadata meta = f.meta # Use the transform in the metadata and your coordinates rowcol = rasterio.transform.rowcol(meta['transform'], xs=latitude, ys=longitude, zs=None) y = rowcol[0] x = rowcol[1] # Load specific pixel only using a window window = Window(x,y,1,1) raster_values = f.read(window=window) return JsonResponse(pixel_value,raster_values, status=status.HTTP_201_CREATED) else: return JsonResponse('Nothing') -
Django CSRF Protection GraphQL API
I do have a graphqlAPI which I use for CRUD Operations to my database. The authentication is tokenbased. So if an user wants to make cruds (mutations) to my database, it needs a valid token in order to do that. What I dont know is if my graphql API is also protected against CSRF attacks as I exempt this protection with csrf_exempt without csrf_exempt it needs a csrf token. Is there a way to ask for a valid csrf token without sending it over the frontend ? The graphql api is only used for the backend for inserting data into the database in which I cant get the csrf token over the frontend. Backend/Frontend: Django Database: Mongo Thanks -
How to include staticfiles in wsgi django project?
Today I ran into a problem connecting static files to my project. If I run django app with command: python manage.py runserver <ip>:<port>then static files are found. If I run the django app as a wsgi service (systemctl start myapp), I get an error that no static files were found. My project in /home/alevt/health_check. I have next structure of project: ---- client -------- manage.py -------- my.ini -------- app ------------ urls.py ------------ settings.py ------------ wsgi.py -------- health_app ------------ urls.py ------------ static --------------- scripts ----------------- myscript.js ------------ templates --------------- index.html settings.py INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'health_app', ...] STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') index.html <script src="{% static 'scripts/myscript.js' %}"></script> ERROR Not Found: /static/scripts/create-table.js my.ini [uwsgi] http = 10.107.14.161:8000 module=app.wsgi:application chdir = /home/alevt/health_check/client/ wsgi-file = /home/alevt/health_check/client/app/wsgi.py virtualenv=/home/alevt/health_check/env single-interpreter = true enable-threads = true master = true And my file of service Description=uWSGI instance to serve myproject [Service] ExecStart=/usr/bin/bash -c 'uwsgi --ini /home/alevt/health_check/client/my.ini' KillSignal=SIGQUIT Type=notify [Install] WantedBy=multi-user.target``` -
Multiple CN LDAP integration in Django project
I want to use multiple CN names in LDAP configurations. I tried to use AUTH_LDAP_REQUIRE_GROUP = "CN=GROUP_NAME1,OU=MSG Distribution Groups,DC=XXX,DC=XXX,DC=XXX" How can I allow multiple groups in CN? Thanks in advance. -
it safe to request url in django? [closed]
I need to check if user submitted url really exists. but I found in some sources that it is not safe to send request from django to the site for this. do you have any suggestions django used to have validation for this but then removed it for security reasons I found code samples: but verify_exists is deprecated for security reasons and has been removed in Django 1.5 -
Cannot connect to redis while using Sentinels in django-redis
Currently I am trying to integrate redis into my django project which is docker based. I was able to integrate redis using the DefaultClient but it doesn't work for SentinelClient My settings.py looks like this: DJANGO_REDIS_CONNECTION_FACTORY = 'django_redis.pool.SentinelConnectionFactory' SENTINELS = [ ('redis://9b39d2b0eb5d', 26379), ] # 9b39d2b0eb5d is the ip of redis sentinel container CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis-queue-1:6379', 'OPTIONS': { 'SENTINELS': SENTINELS, # django_redis.client.SentinelClient 'CLIENT_CLASS': 'django_redis.client.SentinelClient', 'CONNECTION_POOL_CLASS': 'redis.sentinel.SentinelConnectionPool', }, } } It doesn't throw any exception, django just gets stuck on loading -
Django rest framework updating a OneToOne field
I have a User model that inherits from AbstractUser which has an email field. And a profile model that has an OneToOne relation with the User model class User(AbstractUser): email = models.EmailField(unique=True) class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) phone = models.CharField(max_length=13, validators=[phone_regex], unique=True, null=True, blank=True) birth_date = models.DateField(blank=True, null=True) about = models.TextField(max_length=2000, blank=True) def __str__(self): return f"{self.user.first_name} {self.user.last_name}" view.py class ProfileViewSet(ModelViewSet): .... @action(detail=False, methods=["GET", "PUT"], permission_classes=[IsAuthenticated]) def me(self, request, *args, **kwargs): profile = Profile.objects.get(user_id=request.user.id) if request.method == "GET": serializer = ProfileSerializer(profile) return Response(serializer.data) elif request.method == "PUT": serializer = ProfileSerializer(profile, request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) serializers.py class ProfileSerializer(serializers.ModelSerializer): user = CurrentUserSerializer() def update(self, instance, validated_data): user_data = validated_data.pop('user') user_ser = CurrentUserSerializer(instance=instance.user, data=user_data) if user_ser.is_valid(): user_ser.save() instance.phone = validated_data.get('phone', instance.phone) instance.birth_date = validated_data.get('birth_date', instance.birth_date) instance.about = validated_data.get('about', instance.about) instance.save() return instance class Meta: model = Profile fields = [ 'id', 'user', 'phone', 'birth_date', 'about', ] Now when I try to update a user profile I get status: 400 Bad Request error { "user": { "email": [ "user with this email already exists." ] } } using patch instead of put or partial=True doesn't change anything I still get this error. What can I do here? -
Django: Async POST Request
I am trying to make an async post request using the following approach: First of all, I have defined a fixture to return the client: @pytest.fixture(scope="session") async def async_app_client(): async with AsyncClient() as client: yield client Then i use the client to execute the post request. @pytest.mark.asyncio @pytest.mark.django_db() async def test_single_statistic_task_monitoring( async_app_client, statistic_object_univariate ): print(reverse("statistics-list")) response_post = await async_app_client.post( reverse("statistics-list"), statistic_object_univariate, format="json", ) The error i am getting is: AttributeError: 'async_generator' object has no attribute 'post' However, for examples online many use httpx AsyncClient to make the post request. What is the problem here? -
Cannot create a db from scratch after messing with squashmigrations command in django
I tried to run the squashmigrations command in django and after a while I needed to delete the db and start from scratch (the problem also applies when downloading the repository from GitHub and trying to recreate the project). I get the following error when running python manage.py makemigrations or python manage.py migrate error: (venv) meal_plan main python manage.py makemigrations Traceback (most recent call last): File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: meal_plan_recipe The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 22, in <module> main() File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 443, in execute self.check() File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 61, in _load_all_namespaces url_patterns = getattr(resolver, "url_patterns", []) File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = … -
Django - Using Case to update datefield but no effect?
I am trying to update two fields: # This works, changes the correct field. DModel.objects.filter(ticker=i['tic']).filter(trail=True).update( last_high_price=Case( When( LessThan(F('last_high_price'), i['high_price']), then=Value(i['last_high_price'])), default=F('last_high_price') ) ) # Using the same condition to change another field in same row. Does not work? DModel.objects.filter(ticker=i['tic']).filter(trail=True).update( date_high_price=Case( When( LessThan(F('last_high_price'), i['high_price']), then=Value(i['last_date_time'])), output_field=DateField(), default=F('date_high_price') ) ) The field date_high_price will not update, I am getting a 200 response. But the field remains null. If I remove output_field then I get >FieldError. -
I have a two Model related to each other and I want to automatically create the data on ModelB upon creating the data in ModelA
I have this User Model Which came from the User of Django Admin class NewUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) user_name = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name'] def __str__(self): return str(self.id) + " " + self.email And I have another model related to this User model called Promoter model class Promoter(models.Model): user = models.ForeignKey( NewUser, on_delete=models.CASCADE, ) def __str__(self): return str(self.user.id) + " " + self.user.email def email(self): return self.user.email And every time I added a data into User I want to Automatically add also a data into the Promoter model with a link to newly created User This is my code in added/registering a new User class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): newuser = serializer.save() if newuser: return Response(status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I try to manually add the newly created User into the front end by having a two different API call both for adding User and adding promoter but I'm getting an error in adding a Promoter data manually (1048, "Column 'user_id' cannot be null") I also try … -
Best way to config gunicorn and nginx with django?
I am trying to deploy django with gunicorn and nginx on heroku, and i'm kinda confused with the way to config gunicorn and nginx, when i searched through internet, they usually create gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target but when i go to gunicorn docs : https://docs.gunicorn.org/en/stable/deploy.html. nginx has a config file like this worker_processes 1; user nobody nogroup; # 'user nobody nobody;' for systems with 'nobody' as a group instead error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; # increase if you have lots of clients accept_mutex off; # set to 'on' if nginx worker_processes > 1 # 'use epoll;' to enable for Linux 2.6+ # 'use kqueue;' to enable for FreeBSD, OSX } http { include mime.types; # fallback in case we can't determine a type default_type application/octet-stream; access_log /var/log/nginx/access.log combined; sendfile on; upstream app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response # for UNIX domain socket setups server unix:/tmp/gunicorn.sock fail_timeout=0; # for a TCP configuration # … -
'base_tags' is not a registered tag library. Must be one of:
Hello I get this error for create new custom template tags in django how i can debug my code? it's my template tags: from django import template from ..models import Category register = template.Library() @register.simple_tag def title(): return "any thing" it's my HTML code: {% load base_tags%} <a class="navbar-brand" href="index.html">{% title %}</a> it's my error: 'base_tags' is not a registered tag library. Must be one of: admin_list admin_modify admin_urls cache i18n l10n log static tz I run webserver in terminal but for again it's doesn't work true -
How to return queryset based on selected option using AJAX in django?
Here is my view.py : def get_group_ajax(request): if request.method == "GET": g_id = request.GET['group_id'] productlist = models.Stocksupporter.objects.filter(pmaingroups = g_id).values('productname').exclude(numberqut=0) *//This is my queryset* Here is my AJAX and used Django template for loop : $("#allgrp").change(function () { const gId = $('#allgrp').val(); $.ajax({ type: "GET", url: '{% url "webapp:get_group_ajax" %}', data: { 'group_id': gId, }, success: function (data) { html_data = ` {% for pr in productlist %} <div class="cardc" id="card_id"> <p>{{ pr.productname }}</p> </div> {% endfor %} `; $("#card_id2").html(html_data); } }); }); now what is problem: I want return productlist (for loop) in AJAX Success based on selected value (mean group id), i used Response methods but still can not return anything. is there any way for do it? -
CSS not loading on django on different settings environments
I'm using Django as a framework, and I want to hide a column on mobile view with CSS. I use three different settings files: base, dev, and prod. All the main settings are in the base file and the only difference between the dev and prod settings - in what database I'm using (local Postgres and remote Postgres on Railway). I have my base.html file, where I load static files: <head> <meta charset="UTF-8"> <title>{{ title }}</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'main/css/base.css' %}"> <link rel="shortcut icon" type="image/png" href="{% static 'main/img/favicon.ico' %}"/> That's my project structure: I want to hide a column on mobile view, so that's what I have in my base.css: @media only screen and (max-width: 800px) { td:nth-child(1) { display:none; } th:nth-child(1) { display:none; } } However, when I run the app using dev settings - everything works fine. When I run using prod - changes are not displayed. It seems that CSS file is not being read, but I'm wondering why if the code is the same - the difference is only in using different databases on … -
Django complex query with page load slow
I have a quiz application made with Django. I am basically loading a pretty complex query. What I am basically doing is creating a new exam with this logic: Fetch the question from the question bank (the Question model) I get a certain questions number from each subject and I use them to create a QuestionDraft so I can store and save each student result. Each QuestionDraft has the AnswerDraft which I use for storing the user answered questions (each AnswerDraft is basically a carbon copy of the question bank Answer). While I wanna load a 50-question-test everything works pretty fine but when I want to load more than that amount of question, the page is loading extremely slow. I would like to know if, based on the models and the code I post down below, there is any way to improve the efficiency of the queries and/or the loading time. models.py class QuestionSubject(models.Model): quiz_course = models.ForeignKey(QuizTheoryCourse, on_delete=models.CASCADE) name = models.CharField(max_length=200) exam_questions_num = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Question(models.Model): id = models.CharField(max_length=7, default=generate_question_id, unique=True, primary_key=True, editable=False) question_subject = models.ForeignKey( QuestionSubject, on_delete=models.CASCADE) text = models.TextField() mark = models.IntegerField(default=1) is_published = models.BooleanField(default=True) question_bank_id = models.CharField(max_length=255, blank=True, null=True) question_topic … -
Django: error while using DateRangeFilter on a baseadmin
I trying to create a BaseDateAdmin models to use this package: https://github.com/silentsokolov/django-admin-rangefilter for filtering created objects based on the created date. But when I try to add this base model to another admin model which has some 'list_filter' items I get the following error: __init__() missing 2 required positional arguments: 'model_admin' and 'field_path' from rangefilter.filters import DateRangeFilter class BaseDateAdmin(admin.ModelAdmin): def get_list_filter(self, request): res = list(super().get_list_filter(request)) res.extend('created',DateRangeFilter) return list(set(res)) @admin.register(Example) class ExampleAdmin(BaseDateAdmin): list_filter = ( ('in_paid', 'state'), ) -
Can't Assign Tags To Correct Post Through Serialization Using Django Rest Framework
I'm trying to serialize a Tag model for my DRF (Django Rest Framework) project - but somehow I couldn't assign tags to a specific post's title when sending JSON to the API's endpoint. Instead of seeing the correct post title designated with the proper tags, I see this: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "tag id": "9", "post title": "No post title found!", "slug": "test-999", "post id": [], "tag": "test 999" } ] My tag model: class PostTag(models.Model): tag = models.CharField(max_length=50, blank=True) slug = models.SlugField(max_length=255, unique=True) posts = models.ManyToManyField(Post, related_name='post_tag', through='role') def __str__(self): return self.tag My serializers.py: class TagsieSerializer(serializers.ModelSerializer): # posts = serializers.StringRelatedField(many=True, read_only=True) class Meta: model = PostTag fields = '__all__' def to_representation(self, instance): """ Customizing how serialization of each tag should be displayed. This is possible due to overriding to_representation method. :param instance: :return: """ data = super(TagsieSerializer, self).to_representation(instance) for val in [data]: tag_id = str(val['id']) tag = val['tag'] slug = val['slug'] post_id = val['posts'] post_title_list = [] new_post_title_list = [] try: # Getting post title - but for some strange reason ValueError occurs and yet result returns # fine if I catch it and append it inside a list. … -
AssertionError: 200 != 302. Trying to test a redirect from a successful form entry
I'm trying to test redirect from a form using POST. I'm following the mdn web doc tutorial for Django and thought I would see if I could do some of my own test which are not in the tutorial. I'm try to test the book creation form in the tutorial to see if it redirects to book details page which it should do automatically because it's a class based generic view. It works correctly when I test locally but I cannot get the testcase to pass. Thanks for the help in advance. This is the error: > ===================================================================== FAIL: test_redirects_to_book_details_on_success (catalog.tests.test_views.BookCreateView) > ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\makor\mypythonscripts\django_projects\locallibrary\catalog\tests\test_views.py", line 399, in test_redirects_to_book_details_on_success self.assertRedirects(response, reverse('book-detail', kwargs={'pk': 1})) File "C:\Users\makor\mypythonscripts\django_projects\venv\lib\site-packages\django\test\testcases.py", line 512, in assertRedirects self.assertEqual( AssertionError: 200 != 302 : Response didn't redirect as expected: Response code was 200 (expected 302) ---------------------------------------------------------------------- Ran 1 test in 0.341s FAILED (failures=1) Destroying test database for alias 'default'... models.py from django.db import models from django.urls import reverse # Used to generate URLs by reversing the URL pattern. from django.contrib.auth.models import User from datetime import date import uuid # Required for unique book instances class Genre(models.Model): """Model representing book genre.""" name = models.CharField(max_length=200, help_text='Enter … -
Get Absolute URL of image using django-treebeard tree responce
Hello currently i implemanted django-treebeard package for archive tree struture for categories. Here i faced problem in responce with URL of image. i can't see Absolute URL of image categories NOTE - Serializer not working with this recursive tree structure. I already know that you can pass context = {'request':request} in serializer but in my case, it's not working because it is recursive tree structure. views.py class CategoryAPI(APIView): def get(self, request): try: if CategoryModel.objects.count() > 0: categories = CategoryModel.dump_bulk() # serializer = CategorySerializer(instance=categories, many=True) # print(serializer) return Response({"status":True,"categories":categories}, status=status.HTTP_200_OK) else: return Response({'message': 'Categories not found.'}, status=status.HTTP_200_OK) except Exception as e: return Response({'error':str(e)}) APi GET Responce is like this { "status": true, "categories": [ { "data": { "name": "Fruits", "image": "Categories/download_3_Vg6Rv37.jfif" }, "id": 1, "children": [ { "data": { "name": "Apple", "image": "Categories/download_6zbqDvn.jfif" }, "id": 2, "children": [ { "data": { "name": "Green Kasmiri Apple", "image": "Categories/download_2_HaMCXyc.jfif" }, "id": 10 } ] }, { "data": { "name": "Banana", "image": "Categories/download_4_Mn5h9nL.jfif" }, "id": 3 }, { "data": { "name": "Mango", "image": "Categories/download_5_4RkBFcS.jfif" }, "id": 5 }, { "data": { "name": "Orange", "image": "Categories/download_6_vWVEQgm.jfif" }, "id": 4 } ] }, { "data": { "name": "Health", "image": "Categories/images_fwp1mBB.jfif" }, "id": 6 } ] } … -
How do i get the file path from the string
''' txt=r""" AuthorizedCDFPrefix : Comments : Contact : Symantec Corporation DisplayVersion : 7.7.2 HelpLink : http://www.symantec.com/business/support HelpTelephone : 800-342-0652 InstallDate : 20161026 InstallLocation : C:\Program Files\Veritas\ InstallSource : C:\Users\xemukblbexsrv\Desktop\x64\ ModifyPath : "C:\Windows\Installer\{AE93F96C-24C5-4270-AB93-021CA3BD19 9E}\Setup.exe" Publisher : Symantec Corporation Readme : Size : EstimatedSize : 517996 UninstallString : "C:\Windows\Installer\{AE93F96C-24C5-4270-AB93-021CA3BD19 9E}\Setup.exe" -u URLInfoAbout : http://www.symantec.com URLUpdateInfo : http://www.symantec.com/business/support VersionMajor : 7 VersionMinor : 7 WindowsInstaller : 0 Version : 117899266 Language : 1033 DisplayName : Symantec NetBackup Client NoModify : 0 NoRemove : 0 NoRepair : 0 DisplayIcon : "C:\Windows\Installer\{AE93F96C-24C5-4270-AB93-021CA3BD19 9E}\NB_ARP_ICON" PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SO FTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Symante c NetBackup Client PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SO FTWARE\Microsoft\Windows\CurrentVersion\Uninstall PSChildName : Symantec NetBackup Client PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry """ import re pattern = 'DisplayVersion[\s]+:\s(.*)' pattern1 = 'UninstallString[\s]+:\s(.*)\w+' result1 = re.findall(pattern1, txt)[0] print(result1) ''' Need output like this UninstallString : "C:\Windows\Installer{AE93F96C-24C5-4270-AB93-021CA3BD199E}\Setup.exe" -u But i am getting like this "C:\Windows\Installer{AE93F96C-24C5-4270-AB93-021CA3BD1" Not getting entaire line beacause remaining string will be in next line Some one can help in this @python -
Boolean 'Complete' field in my form is not working from UpdateView in Django
This is the code that I have written. I am facing an issue in implementing the boolean checkbox functionality from UpdateView in Django. When I write complete.save() in below code, I am getting the desired result, but the command 'complete.save()' is getting printed on the form. {% extends 'baseapp/main.html' %} {% block content %} <div class="body"> <h3 class="header-bar" id="add-header">Add Your Task</h3> <form method="POST" action=""> {%csrf_token%} <!--This is used to protect forgery requets--> {{form.as_p}} complete.save() <input class="search-button" type="submit" value="Submit"> <a id="cancel-icon" href="{% url 'tasks' %}"> Cancel</a> <!--If we don't want to create an item--> </form> </div> {% endblock content %} Output of the above code: But, if I do not write it, the checkbox functionality doesn't work. And I redirected to the previous page. Can someone please help me out with this? I am trying to implement the boolean field in UpdateView of Django. -
Pytest with django celery
I have celery task which create models entries in database. Celery uses Redis as a broker. Celery config in settings.py: CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'django-db' from .models import Message @shared_task(ignore_result=True) def create_entries(data: list): batch_size = 100 obj_iterator = (Message(**obj) for obj in data) while True: batch = list(islice(obj_iterator, batch_size)) if not batch: break Message.objects.bulk_create(batch, batch_size) In application everything works fine, but tests don't work. Test method code: @pytest.mark.django_db @pytest.mark.celery def test_create_entries(): message_data = [ { text: 'hello bro', client: 'Nick' }, ] assert Message.objects.count() == 0 task = tasks.create_model_entries.delay(message_data) result = AsyncResult(task.task_id) assert result.status == 'SUCCESS' # here is a fail, status = PENDING assert Message.objects.count() == 1 # here is a fail, count = 0 But if run server: python manage.py runserver and run tasks, then entries are created successfully. What could be the reason that tasks don't work in tests? -
Django not recognizing app_label meta data
Problem I have multiple DBs to connect to for different apps on my django server, which only serves datas from the DB. I recently added new DB and ran python3 manage.py inspectdb --database=new_db, then I added app_label for correct DB connection. But somehow django is keep returning programming error with invalid object name error. I double checked, and DB and tables are exactly there. Then I found out that model was trying to connect to its default database, which doesn't have table I am trying to connect to. What should I try to fix this? Summaries django model is trying to connect to its default DB, inspite it has explicitly declared target DB on its Meta part. DB declaration seems to be fine, because inspectdb was done perfectly. There's no typo on db declaration, too. <DB declaration on 'settings.py'> DATABASES = { 'default' : { 'ENGINE' : 'mssql', 'NAME' : 'DEFAULT_DB', 'USER' : env('DB_USER'), 'PASSWORD' : env('DB_PASSWORD'), 'HOST' : env('DB_HOST'), 'PORT' : env('DB_PORT'), }, 'new_db' : { 'ENGINE' : 'mssql', 'NAME' : 'NEW_DB', 'USER' : env('DB_USER'), 'PASSWORD' : env('DB_PASSWORD'), 'HOST' : env('DB_HOST'), 'PORT' : env('DB_PORT'), } } <Meta data of 'models.py'> class Meta: managed = False app_label='new_db' db_table='NEW_TB'