Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django doesn't connect to postgresql database using docker-compose
Yes i know this question has been asked, and the usual error is making the DB_HOST = docker service name, in my case db. Here's my docker-compose.yml: version: "3" services: db: image: postgres:latest restart: always ports: - "54320:5432" expose: - "54320" volumes: - ./database-data:/var/lib/postgresql/data/ # persist data even if container shuts down environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres # POSTGRES_HOST_AUTH_METHOD: trust django: build: ./api restart: always command: ["python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - ./api:/app/api ports: - "8000:8000" depends_on: - db raddl_admin: build: ./frontend/raddl_admin stdin_open: true # docker run -i tty: true # docker run -t command: ["npm", "start"] ports: - "3000:3000" volumes: - ./frontend/raddl_admin:/app/frontend/raddl_admin - /app/frontend/raddl_admin/node_modules volumes: database-data: # named volumes can be managed easier using docker-compose Logging the django service gives: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "db" (172.18.0.2) and accepting TCP/IP connections on port 54320? So it's clearly trying to connect to db on that port and my environment vars are set for the django instance. I can even ping my db service from my django service: docker exec -it 1f764333ace2 bash | ping db PING db (23.221.222.250): 56 data bytes 64 bytes from 23.221.222.250: icmp_seq=0 ttl=50 time=42.055 ms … -
Which technique for database design is better for performance?
I need to create a Django PostgreSQL Database with a field in multiple tables to use it like a filter for the users, but I don't know what technique to use for performance. I can create a table with the field and make a foreign key for every table. class Tablefilter(models.Model): filter_field = models.Field() class Tablefilted(models.Model): table_filter = models.ForeignKey(Tablefilter) Or in my models just create a extend for that field in every model. class Tablefilter(models.Model): filter_field = models.Field() class Tablefilted(Tablefilter): field = models.Field() -
Django Value Error "seek of closed file" using PIL for image resize when updating a record
I have the following model: class Players(models.Model): team = models.ForeignKey(Teams, verbose_name=_('Team'), on_delete=models.CASCADE) player_name = models.CharField(_('Player Name'),max_length=200) player_description = models.TextField(_('Player Description')) player_image = models.ImageField(_('Profile Pic'),upload_to='upload/player_image', null=True, blank=True) player_social = models.CharField(_('Social Media Tag'),max_length=200) class Meta: verbose_name = _("Players") verbose_name_plural = _("Players") def __str__(self): return self.team.team_name + ' - ' + self.player_name def save(self, *args, **kwargs): super().save(*args, **kwargs) if self.player_image: image_resize(self.player_image, 250) The last function will call another for image resizing taking the file and an expected max width: # Use PIL to resize images; set target width on each def image_resize(image, tgt_width): img = PIL.Image.open(image) img.load() width, height = img.size target_width = tgt_width h_coefficient = width/tgt_width target_height = height/h_coefficient img = img.resize((int(target_width), int(target_height)), PIL.Image.ANTIALIAS) img.save(image.path, quality=100) img.close() image.close() My view for updating is as follows: @method_decorator(superuser_required, name='dispatch') class PlayerUpdateView(UpdateView): model = Players template_name = 'scoreboard/players/player_update.html' form_class = PlayersForm context_object_name: str = 'player' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) team_id = Players.objects.get(pk=self.kwargs['pk']).team.id context["team"] = Teams.objects.get(pk=team_id) return context def form_valid(self, form): form.save() return super().form_valid(form) def get_success_url(self): team_id = Players.objects.get(pk=self.kwargs['pk']).team.id return reverse_lazy('team_detail', kwargs={'pk': team_id}) It doesn't matter if I provide a new image file or not, I get the same "seek of closed file" error: File "D:\00_www\hts-score\overlay\scoreboard\models.py", line 62, in save image_resize(self.player_image, 250) File "D:\00_www\hts-score\overlay\scoreboard\models.py", … -
Django3 Paginator with function based view
class ProductList(ListView): model = Product paginate_by = 8 def company_page(request, slug): ... product_list = Product.objects.filter(company=company).order_by('-pk') paginator = Paginator(product_list, 4) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'product/product_list.html', { ..., 'product_list': product_list, 'page_obj': page_obj }) views.py <nav aria-label="Pagination"> <ul class="pagination justify-content-center my-5"> {% if page_obj.has_previous %} <li class="page-item mx-auto lead"> <a class="page-link" href="?page={{page_obj.previous_page_number}}" tabindex="-1" aria-disabled="true"> Newer</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1" aria-disabled="true"> Newer</a> </li> {% endif %} {% if page_obj.has_next %} <li class="page-item mx-auto lead"> <a class="page-link" href="?page={{page_obj.next_page_number}}"> Older</a> </li> {% else %} <li class="page-item disabled mx-auto lead"> <a class="page-link" href="#!"> Older</a> </li> {% endif %} </ul> </nav> product_list.html Pagination works well on ProductList view but it doesn't on company_page view. The Newer & Older buttons work but the page keeps showing every product_list objects. -
Django REST Framework - Custom action to use different serializer class, empty result
I'm trying to define a custom action which will use a different serializer class, but I'm getting an empty result from that action and I'm not sure why. I've based my action definition code on the DRF documentation, but there may be something that I'm missing, since this is new to me. I have a simple example based on Authors & Books to demonstrate this. Here is my viewset code, and the action where I think the solution may lie: class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() serializer_class = AuthorSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['first_name', 'last_name'] @action(detail=False, serializer_class=AuthorNoBookListSerializer) def no_booklist(self, request): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have two serializers: One with each author's list of books, and one without: class AuthorSerializer(serializers.ModelSerializer): book_list = serializers.ListField(source='books') class Meta: model = Author fields = ('id', 'first_name', 'last_name', 'book_list') class AuthorNoBookListSerializer(serializers.ModelSerializer): class Meta: model = Author fields = ('id', 'first_name', 'last_name') If I swap out serializer_class = AuthorSerializer for serializer_class = AuthorNoBookListSerializer in the viewset, I can see that both serializers work fine: Using AuthorSerializer: HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "count": 4, "next": null, "previous": null, "results": [ { "id": … -
/bin/bash: line 1: gunicorn: command not found
can anyone help us with this problem I am trying to deploy Django application on the railway but got an error /bin/bash: line 1: gunicorn: command not found my gunicorn path /usr/local/lib/python3.10/dist-packages python path ['', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/root/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/local/lib/python3.10/dist-packages/drupwn-1.0.3-py3.10.egg', '/usr/local/lib/python3.10/dist-packages/prompt_toolkit-2.0.7-py3.10.egg', '/root/droopescan', '/usr/lib/python3/dist-packages', '/usr/lib/python3.10/dist-packages'] I tried to add a path but I am not able to do it. Can anyone please help me to solve this problem? -
Error while working on the site in Django
This is a continuation of the previous question. When I continued to work on the site and when I wanted to test the site through "python manage.py runserver" in the C:\mysite\site\miniproject directory, the following error pops up: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Program Files\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Program Files\Python36\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Program Files\Python36\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Program Files\Python36\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Program Files\Python36\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Program Files\Python36\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 674, in exec_module File "<frozen importlib._bootstrap_external>", line 781, in get_code File "<frozen importlib._bootstrap_external>", line 741, in source_to_code File "<frozen … -
Django: Handling of duplicated values on unique rows
I have a row of data and in it consist of Protein object. Protein Object has unique protein_id (not PK) and rows of data can have repeatable protein object. So when a user creates a row of data say Data: {'protein_id':ABC123} if the given protein_id already exists in database, we'll use that protein object. I am able to create the protein object when it does not exist in database. But when it already exist, I am getting "protein with this protein id already exists.". I understand that this happens because I am creating new protein object with the same protein_id and protein_id has a unique=True attribute. But what I am not understanding is (Refer below for details) why I am unable to get the object if exist or why is the exception getting thrown (Not sure whats the logic behind). Models.py class Protein(models.Model): protein_id = models.CharField(max_length=256, null=False, blank=False,unique=True) sequence = models.CharField(max_length=40000,blank=True) Serializer.py class ProteinSerializer(serializers.ModelSerializer): class Meta: model = Protein fields = ['protein_id',"sequence"] def create(self,validated_data): protein_data = validated_data.pop('protein') protein = None try: protein = Protein.objects.get(protein_id=protein_data['protein_id']) except Protein.DoesNotExist: protein = Protein.objects.create(**protein_data) return protein What I have tried here is a try-except where the serializer will first get the protein object in database … -
Django : get context data dynamically
I'm working on a music web app and trying to display chart (with Chart.js) for genres by family (ie indie Rock genre is in the rock family). I have 14 families (Rock, Metal, Jazz, etc...) and want to be able to select one of them to display how many albums for each genre of the family selected. So here's my code: My View, in which I send metal, rock and hip hop families genres and album number in the context : class StatsAlbumView(ListView): model = Album queryset = Album.objects.all() template_name = "statistic/album.html" context_object_name = "albums" def get_queryset(self): queryset = super().get_queryset() self.filterset = AlbumFilter(self.request.GET, queryset=queryset) return self.filterset.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) all_families = api.get_all_families() context['all_families'] = all_families metal, albums_metal = api.get_album_by_family_genres("Metal") context['metal'] = metal context['albums_metal'] = albums_metal rock, albums_rock = api.get_album_by_family_genres("Rock") context['rock'] = rock context['albums_rock'] = albums_rock hip_hop, albums_hip_hop = api.get_album_by_family_genres("Hip-Hop") context['hip_hop'] = hip_hop context['albums_hip_hop'] = albums_hip_hop context['form'] = self.filterset.form return context My api file in which I get the data I need : def get_album_by_family_genres(family): genres = Genre.objects.filter(family=family) albums = Album.objects.all() albums_from_family = [] for album in albums: album_list_genre = list(album.genre_primary.all()) for genre in album_list_genre: if genre in genres: albums_from_family.append(album) print(albums_from_family) if albums_from_family: list_genres, list_albums_number = get_album_by_primary_genre(albums_from_family, family) … -
How to use function of a class as decorator which itself takes a parameter in python?
I tried this below snippet as an experiment as how decorators can be used in various scenario , here without s variable the the whole code is working but when I add an argument in decorator function is shows error message. class dec(object): def __init__(self, str1, str2): self.str1 = str1 self.str2 = str2 print(f"printing from init via ----- str1={self.str1} , str2={self.str2}") def onef(self,f,s): print(f"printing from init via onef ----- str1={self.str1} , str2={self.str2}") print("onef --------- up") f() print(f"printing s = {s}") print("onef --------- down") d=dec(str1='Hey',str2='hi') @d.onef(s='in onef ok !') def f(): print("The F --- function") error message printing from init via ----- str1=Hey , str2=hi Traceback (most recent call last): File "C:\Users\Anuj\Desktop\decorators.py", line 16, in <module> @d.onef(s='in onef ok !') TypeError: dec.onef() missing 1 required positional argument: 'f' Previously tried this one. class dec(object): def __init__(self, str1, str2): self.str1 = str1 self.str2 = str2 print(f"printing from init via ----- str1={self.str1} , str2={self.str2}") def onef(self,f): print(f"printing from init via onef ----- str1={self.str1} , str2={self.str2}") print("onef --------- up") f() print("onef --------- down") d=dec(str1='Hey',str2='hi') @d.onef def f(): print("The F --- function") It worked. Answer printing from init via ----- str1=Hey , str2=hi printing from init via onef ----- str1=Hey , str2=hi onef --------- up … -
How to use js on change event with formset django?
There are task types in the field I created with formset. I want to create a new form for the user according to the task types selection. For example, when the user selects the product purchase, I want to copy the same form again. Based on my research i found out that i need to use on change for this but I have no idea how to implement it. Here is my forms : class UserTaskForm(forms.ModelForm): class Meta: model = UserTask fields = ['user_id','task_types_id','store_house_id','description'] UserTaskFormFormSet = modelformset_factory( UserTask, fields=('user_id','task_types_id','store_house_id','description',), extra=1, ) here is my html : {% extends "main/layout.html" %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-md-6 offset-md-3"> <h3 align="center">Add New Task</h3> <hr> <form id="form-container" method="POST"> {% csrf_token %} {{ user_task_form.management_form }} {% for user_form in user_task_form %} <div class="usertask-form" id="usertask-form"> {{user_form | crispy}} </div> {% endfor %} {{ formset.management_form }} {% for form in formset %} <div class="tasksources-form" id="tasksources-form"> {{form | crispy}} </div> {% endfor %} <button id="add-form" class="btn btn-success">+Add More Product</button> <br> <br> <button type="submit" class="btn btn-outline-info">Add New Task</button> </form> </div> </div> <script> let tasksourcesForm = document.querySelectorAll(".tasksources-form") let container = document.querySelector("#form-container") let addButton = document.querySelector("#add-form") let totalForms = document.querySelector("#id_formset-TOTAL_FORMS") let formNum = tasksourcesForm.length-1 … -
Extending django-graphql-auth to constrain username, passwords and emails
I am using Django v 3.2 and django-graphql-auth v 0.3.16 I have a custom User (and User Manager) defined like this: models.py class CustomUser(AbstractUser): USERNAME_FIELD='username' EMAIL_FIELD='email' # ... objects = CustomUserManager() managers.py class CustomUserManager(BaseUserManager): # ... def create_user(self, email, password, **extra_fields): if not is_valid_email(email): raise ValueError(_('Bad email')) username = extra_fields.get('username') if not is_acceptable_username(username)): raise ValueError(_('You cannot use this username')) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) settings.py # .... AUTH_USER_MODEL='myapp.CustomUser' schema.py import graphene from graphql_auth import mutations from graphql_auth.schema import MeQuery, UserQuery class AuthMutation(graphene.ObjectType): register = mutations.Register.Field() verify_account = mutations.VerifyAccount.Field() class Query(UserQuery, MeQuery, graphene.ObjectType): pass class Mutation(AuthMutation, graphene.ObjectType): pass schema = graphene.Schema(query=Query, mutation=Mutation) I try to register a new user through the following mutation: mutation { register( email: "memyself@somebad-domain.com", username: "badword1", password1: "1234", password2: "1234" ) { success errors token } } And I get the following response: { "data": { "register": { "success": true, "errors": null, "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImJhZHdvcmQxIiwiZXhwIjoxNjY5OTEzNDIzLCJvcmlnSWF0IjoxNjY5OTEzMTIzfQ.TZ-copVrhUUsuLpozi18THjprGMnAGsBwpnyWORc16M" } } … -
Django How To Add Number From Other Object
How can i add an int value inside of a field in multiple object to be displayed in another object. Lets say that i need to add all of the item that the customer have ordered previously and store them inside of all_previous_orders. Result.json [ { "customer_name": "John Doe", "order": [ { "order_name": "fruit", "how_many_order": 10, }, { "order_name": "car", "how_many_order": 1, }, ], "all_previous_orders": 11 }, ] Models.py class Customer(models.Model): customer_name = models.CharField(max_length=100) class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) order_name = models.CharField(max_length=100) how_many_order = models.IntegerField(default=0) Serializers.py class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' class CustomerSerializer(serializers.ModelSerializer): orders = OrderSerializer(many=True, read_only=True, required=False) class Meta: model = Customer fields = '__all__' -
Django Forum | Post Question | Save Data in JavaScript Variable doesn't work
I'm currently making a Forum using Django and I have a problem. When making the "Post Question" Page. I want to save the title, description, etc. in a javascript variable because you enter the data through several pages. (see here: Post Question Title & here Post Question Description). Using this JavaScript Code: ` let post = []; function next() { let title = document.getElementById("title"); if(title.value == "" || title.value == " "){ alert("Please fill out the title field"); } else { post[0] = title.value link(); } } function next_description(){ let description = document.getElementById("description"); if(description.value == "" || description.value == " "){ alert("Please fill out the description field") } else { post[1] = description.value console.log("Title: " + post[0], "\nDescription: "+ post[1]) } } function next_tags(){ link_tags(); } function finish(){ link_finish(); } ` For test purposes I am logging the Data from the JavaScript Array when clicking the Next button in the Description File. Looking in the Dev Tools I see this: Title: undefined Description: Hello World! Why so? And How can I implement this better? -
How to annotate the sum of 2 columns in Django, when one needs to be filtered and the other parsed first?
I have x, a ManyToManyField that I want filtered by name. This can be achieved by count1 = Q(x__name__contains=UNSUPPORTED_FORMATS) I also have y, a JSONField which is really a list. I want to count the elements inside as well, after I filter out irrelevant elements. Can be achieved by count2 = len(list(filter(lambda y: not y.endswith(tuple(UNSUPPORTED_FORMATS)), object.y))) Now I'd like to annotate an entire queryset of object, with a column that equals count1 + count2 How can I create this annotation? -
Multiple choice in model
ANIMALS = (('dog','dog'), ('cat','cat')) class Owner(models.Model): animal = models.Charfield(choices=ANIMALS, max_length=10) My problem is how I can do if I have both ? -
Django-filer problem when retrieve uploaded image in Django admin interface or any http|s request
I'm a noob in Django framework, sorry for misunderstanding in some concepts. Currently, I'm trying to set up a Django app with django-filer. Django filer was installed commonly and migrations were done according to documentation. The installed apps list was updated with filer, mptt, and easy_thumbnails. The allowed host was updated with the IP of the host, debug flag was set to true and timezones and language code were also updated, as shown below. According to documentation, that's all for a basic setup of Django filer. from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = ["192.168.230.98"] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'filer', 'mptt', 'easy_thumbnails' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'filerTest.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'filerTest.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } USE_I18N = True USE_TZ = True STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' Two images were uploaded through the Django admin interface. After images are upload, the Django admin interface can't retrieve they. Chrome development console showed … -
How to get element id with foreignkey in admin.py
I have a question. Can i pass the data for filtering another field(manytomany) in admin.py ? I need to get linked foreignkey id value. Models.py class Pansions(models.Model): ...... category = models.ForeignKey(Category, null=True, on_delete=models.PROTECT, related_name='cards', verbose_name='Category') ...... Admin.py class PansionatAdmin(admin.ModelAdmin): ..... fields = ('title', 'slug', 'category', 'tags') .... def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "tags": kwargs["queryset"] = Tag.objects.filter(category__id = "GET ID FOREIGNKEY_FIELD (caterogy)") return super().formfield_for_manytomany(db_field, request, **kwargs) I try to get data from models.py, but it not happen. Is it possible? -
Selenium chromdriver keeps on giving me error
I have been able to make use of selenium chrome for a sometime. I have tried to catch an error using try: #check if it already exist before doing anything webdriver.driver except: chromeBrowser=ChromeDriverManager().install() ....... some other code here The above code works very well, it catches the error and loads the browser without any problem. Suddenly it started giving me this error and it does not go beyond that. It does not even go into the internet at all. ERROR: The system was unable to find the specified registry key or value. Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\pure_spring\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\pure_spring\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\python_src\school\school\host\views.py", line 2333, in loopTest chromeBrowser = ChromeDriverManager().install() File "C:\python_src\venv\lib\site-packages\webdriver_manager\chrome.py", line 23, in __init__ self.driver = ChromeDriver(name=name, File "C:\python_src\venv\lib\site-packages\webdriver_manager\driver.py", line 54, in __init__ self.browser_version = chrome_version(chrome_type) File "C:\python_src\venv\lib\site-packages\webdriver_manager\utils.py", line 155, in chrome_version raise ValueError(f'Could not get version for Chrome with this command: {cmd}') ValueError: Could not get version for Chrome with this command: reg query "HKEY_CURRENT_USER\Software\Google\Chrome\BLBe acon" /v version --- Logging error --- Traceback (most recent call last): File "C:\Users\pure_spring\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 1081, in emit msg = self.format(record) File "C:\Users\pure_spring\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 925, in format … -
My html elements are not in the proper place
I am using bootstrap classes and for some reason they are not working. This is the combined templates. The ones that are switching are <div class="col-md-8"> and <div class="col-md-4" style="margin: 0;"> {% load static %} {% csrf_token %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="viewport"> <meta name="Description" content="Yoder Blog is a Custom Blog made with html css javascript and most of all python. In this version of Yoder Blog, I use django. This is a Blog mainly used by the, as you guessed it, Yoders."> <meta name="KeyWords" content="Yoder Blog, yoder blog, jdswebsites.xyz, jdoder"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="shortcut icon" href="{% static 'favicon.ico' %}" type="image/x-icon"> <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}"> {% if user.is_authenticated %} {% if user.profile.theme %} <link rel="stylesheet" type="text/css" href="{% static 'light.css' %}"> {% else %} <link rel="stylesheet" type="text/css" href="{% static 'dark.css' %}"> {% endif %} {% else %} <link rel="stylesheet" type="text/css" href="{% static 'light.css' %}"> {% endif %} {% if title %} <title>Yoder Blog - {{ title }}</title> {% else %} <title>Yoder Blog</title> {% endif %} </head> <body> {% csrf_token %} <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> … -
Better way to add multiple field to this model?
In my Django project I have a model for a drinks recipe that allows up to 10 ingredients plus their amount. I am wondering if it's possible to make this in a more DRY way than I do now? This is the model I am using currently: class Recipe(models.Model): ingr_name1 = models.CharField(max_length=250, verbose_name='Ingredient') ingr_amount1 = models.DecimalField(max_digits=5, decimal_places=1, verbose_name='Amount') ingr_name2 = models.CharField(max_length=250, blank=True, null=True, verbose_name='Ingredient') ingr_amount2 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name3 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount3 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name4 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount4 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name5 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount5 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name6 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount6 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name7 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount7 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name8 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount8 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name9 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount9 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') ingr_name10 = models.CharField(max_length=250,blank=True, null=True, verbose_name='Ingredient') ingr_amount10 = models.DecimalField(max_digits=5, decimal_places=1,blank=True, null=True, verbose_name='Amount') drink_name = models.CharField(max_length=250,blank=True, null=True, verbose_name='Drink name') drink_story = models.TextField() drink_picture = ResizedImageField(upload_to='drinks/', null=True, blank=True) def __str__(self): return self.drink_name -
Django wizard form goes to the prev step instead of next step
I have a 3 step form. So when I'm at the second step and hit enter, it goes to the prev step instead of next step. This is my set up: forms.py class ContactForm1(forms.Form): subject = forms.CharField(max_length=100) class ContactForm2(forms.Form): sender = forms.CharField(max_length=100) class ContactForm3(forms.Form): message = forms.CharField(widget=forms.Textarea) views.py class Prueba(SessionWizardView): template_name = 'start.html' form_list = [ContactForm1, ContactForm2, ContactForm3] def done(self, form_list, **kwargs): return render(self.request, 'done.html', { 'form_data': [form.cleaned_data for form in form_list], }) urls.py urlpatterns = [ path('prueba', Prueba.as_view(), name='prueba') ] start.html <form action="" method="post"> {% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form.as_table }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} <input id='btncont' type="submit" value="Continuar"/> </form> I've use this jquery code but doesn't work because when I press enter, goes to the prev step. $(document).ready(function(){ $('#id_1-sender').keypress(function(e){ if(e.keyCode==13) $('#btncont').click(); }); }); -
How to iterate javascript function in rows?
I created a search and highlight field for my model objects. The page takes a text input and filtering the objects like Documents.objects.filter(content) I'm using read more and highlight functions to highlight the input word and show the a part of the long content. But I can't click some read mores on the row. For example I can't click 1st and 3rd row (it returns javascriot:void(0) but there is no action) but I can click the other rows. I couldn't find why? <td> <div id="highlights" > <div class="row"> <div class="col-md-12" > <div class="box"> <p class="countParawords-{{ forloop.counter }}" id="paragraph-{{ forloop.counter }}"> {{ document.content }} </p> </div> </div> <input id="typed-text-{{ forloop.counter }}" type="text" class="hidden_input" placeholder="Type text" value="{{ key_word }}"> </div> </div> </td> <script> {% for doc in documents %} var opar = document.getElementById('paragraph-{{ forloop.counter }}').innerHTML; $(document).ready(function() { var maxLength = 300; var moretxt = "...Read More"; var lesstxt = "...Read Less"; $(".countParawords-{{ forloop.counter }}").each(function() { if(opar) { var paragraph = (document.getElementById('paragraph-{{ forloop.counter }}')); var search = document.getElementById('typed-text-{{ forloop.counter }}').value; search = search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); var re = new RegExp(search, 'g'); if (search.length > 0) paragraph.innerHTML = opar.replace(re, `<span style="background: #cead00">$&</span>`); } else{ console.log("No data") } var myStr = paragraph.innerHTML if ($.trim(myStr).length > maxLength) … -
Having trouble accessing a Django database from a Python project
I’m trying to do a rudimentary connect to a database I created in a Django project (in PyCharm) from another (new) Python project in PyCharm and struggling to even get a list of tables displaying from Python. Could anyone advise on what I might be doing wrong, am I setting the name of the database incorrectly or do I need to do some step before this to connect a name to the database? I have the following connection (right panel): And my code is as follows (copied from an example): import sqlite3 try: # Making a connection between sqlite3 # database and Python Program sqliteConnection = sqlite3.connect('identifier.sqlite') # If sqlite3 makes a connection with python # program then it will print "Connected to SQLite" # Otherwise it will show errors print("Connected to SQLite") # Getting all tables from sqlite_master sql_query = """SELECT name FROM sqlite_master WHERE type='table';""" # Creating cursor object using connection object cursor = sqliteConnection.cursor() # executing our sql query cursor.execute(sql_query) print("List of tables\n") # printing all tables list print(cursor.fetchall()) except sqlite3.Error as error: print("Failed to execute the above query", error) finally: # Inside Finally Block, If connection is # open, we need to close it if sqliteConnection: … -
Cannot create URL for blob! error in react native
I am trying to send a formdata consisting of image to backend server. However I am getting cannot create url for blob error This is my code for selecting file: const selectFile = async () => { // Opening Document Picker to select one file try { const res = await DocumentPicker.pickSingle({ type: [DocumentPicker.types.allFiles], }); console.log('res simple', res); console.log('res : ' + JSON.stringify(res)); //fetch uri from the response const fileUri = res.uri; console.log('res : ' + fileUri); setSingleFile(res); // handleAcceptedFiles(res); } catch (err) { setSingleFile(null); if (DocumentPicker.isCancel(err)) { ToastAndroid.show('Canceled', ToastAndroid.SHORT); } else { alert('Unknown Error: ' + JSON.stringify(err)); throw err; } } }; And this for getting the blob: useEffect(() => { if (singleFile != null) { getData(); } }, [singleFile]); const getData = async () => { console.log('inside getData'); // console.log("singleFile",singleFile) console.log('singlefile', singleFile.uri); const response= await fetch(singleFile.uri) const blob = await response.blob() console.log('blob', typeof(blob)); const ur= URL.createObjectURL(blob) console.log('ur', ur); setBlob(blob); }