Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Best way to structure a database when giving the user the ability to create dynamic fields
I would like some advice on the best way to structure some models in a django project I have. I need to give the user the ability to create their own verticals, which dictates what fields the "client" object will have. Here are two example verticals to illustrate this: Loan Fields: name (str field) phone (str field) loan_amount (int field) loan_purpose (selection field) Solar Fields: name (str field) phone (str field) house_type (selection field) budget (int field) So right now I have a Vertical model, and a DataField model that has a foreign key relationship with a vertical. That way users can dynamically create fields for each vertical they have. To save incoming clients, I have a Client model. The Client model has a foreign relationship with a vertical, so the user knows which vertical it belongs to. However, since datafields are dynamically set by the user, I can't simply set datafields as fields on the Client model. As such, I currently have a model called ClientField. The ClientField has a fk relation to a Client and to a DataField, and also a normal field "value" to store the value of that field. So when a Client is created, I … -
How to make Djano redirect after validating an uploaded file?
Instead, the page just reloads. When I check my server logs nothing is happening. This tells me that either the page isn't uploading or my views.py has a problem but I'm not sure what that could be. Here is my code: HTML: <form method="post" action="{% url 'transcribeSubmit' %}" enctype="multipart/form-data" > {% csrf_token %} <label for="transcribe-file" class="transcribe-file-label"> <input id="transcribe-file" name="audio-video" type="file" accept="audio/*, video/*" hidden> <button class="upload" id="transcribe-submit" type="submit" >Submit</button> JS: document.getElementById("transcribe-file").addEventListener("change", function(event){ document.getElementById("transcribe-submit").click(); }); views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from django.http import JsonResponse from django.views.decorators.csrf import csrf_protect from .models import TranscribedDocument from .forms import UploadFileForm from django.core.files.storage import FileSystemStorage # Create your views here. @csrf_protect def transcribeSubmit(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) try: if form.is_valid(): audio_file = form.save() return redirect('/t/') except Exception as e: print(f"An error occurred: {e}") error_message = f"An error occurred: {e}" return JsonResponse({'error': error_message}, status=500) else: form = UploadFileForm() return render(request,'transcribe/transcribe.html', {'form': form}) forms.py: from django import forms import mimetypes import magic from django.core.exceptions import ValidationError def validate_file(file): # Validate if no file submitted (size = None) if file is None: raise ValidationError("No file submitted") else: #Check file size fileSize = file.size maxSize = 5242880 # 5MB in bytes (also: … -
Django models update related object when relation is updated
Ruby on Rails has a notion called touch. This is helpful in situations where you have objects linked via foreign keys and you want to conditionally update, say the parent's updated_at field, whenever the child is updated. This can then be used efficiently for Russian Doll caching amongst other useful things. Per the Rails docs: class Product < ApplicationRecord has_many :games end class Game < ApplicationRecord belongs_to :product, touch: true end With touch set to true, any action which changes updated_at for a game record will also change it for the associated product, thereby expiring the cache. I tried to find an equivalent way in Django for achieving this but I haven't found an elegant solution. How can I force update Product.updated_at whenever Game.updated_at is altered? class Product(models.Model): updated_at = models. DateTimeField() class Game(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) updated_at = models. DateTimeField() Thanks!! -
ValueError: No route found for path 'ws/chat/AUdZzo8slKKwKvzmUrnmLRfnVkuAYfJj/'
I am working on a django chatting application that uses websockets to carry out its chatting functionality. I am getting the following error in daphne: Traceback (most recent call last): File "/home/gamedeveloper/venv/lib/python3.11/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/gamedeveloper/venv/lib/python3.11/site-packages/channels/routing.py", line 62, in __call__ return await application(scope, receive, send) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/gamedeveloper/venv/lib/python3.11/site-packages/channels/routing.py", line 134, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/chat/AUdZzo8slKKwKvzmUrnmLRfnVkuAYfJj/'. I ran the following daphne command using ubuntu on my remote server: (venv) gamedeveloper@animechatapp:~/anime_chat/anime_chat_app$ daphne -u /tmp/daphne.sock --bind my.ip.address -p 8001 anime_chat_app.asgi:application I figured that there might be some issues with my firewall settings on my remote server so I made some changes and allowed traffic on port 8001 but I am still getting the error. The following is the JS code I am using to establish connection with the websocket: const chatSocket = new WebSocket( (window.location.protocol === 'https:' ? 'wss://' : 'ws://') + window.location.host + '/ws//chat/' + roomName + '/' ); The following is the output inside my console window WebSocket connection to 'ws://194.195.119.237/ws/chat/AUdZzo8slKKwKvzmUrnmLRfnVkuAYfJj/' failed: The following is routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^ws://chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer.as_asgi()) ] … -
Is there a python pip package or similar for mapping a name to a nickname. So for example package_name['Joseph'] would return 'Joe' for example?
I am building an app where I have a database of thousands of names, I then use have a second source of data that I am mapping the first data to to find something, however I'm facing an issue where sometimes in one database I have the name 'Joseph' for example, but when im trying to find it in the second source of data, the name is 'Joe'. Already tried looking on pip but no luck -
Django modeltranslation adds ALL available languages to our table - not only the ones we want - why?
Today we evaluated django-modeltranslation for our project - and it looks good. There's only one caveat: on our table all available python languages are added - not only the ones we need. In the documentation it says: "Warning - Modeltranslation does not enforce the LANGUAGES setting to be defined in your project. When it isn’t present (and neither is MODELTRANSLATION_LANGUAGES), it defaults to Django’s global LANGUAGES setting instead, and that are quite a few languages!" Fair enough - but we have languages defined in settings.py: LANGUAGES = [ ('en', _('English')), ('de', _('German')), ] LANGUAGE_CODE = 'de' MODELTRANSLATION_LANGUAGES = ('en', 'de') MODELTRANSLATION_DEFAULT_LANGUAGE = 'en' MODELTRANSLATION_PREPOPULATE_LANGUAGE = 'en' MODELTRANSLATION_FALLBACK_LANGUAGES = ('en', 'de') MODELTRANSLATION_TRANSLATION_FILES = ( 'salesUnit.translation', ) Any ideas why columns for all languages are generated on our table? -
CGI deployment for a Django Webapp e.g. Strato.de Webhosting
iam trying to deploy my django app via cgi on strato.de . Strato only supports basic cgi so iam forced to use this method. I already made a flask app run on strato via cgi with this tutorial ( btw great guide ). I tried to alter this and adept it to the django app to get it running on the webserver, but it looks like i am missing something. If i call the website i run into an 500 Internal Server Error . ( I would apprieciate also some tipps how to debug this, I have no idea where to start ). Just to mention it: Everything works fine in develompent env. Steps already done: I did check if all required packages are installed on the server listed in the requirements.txt file. I did create an cgi file to load the django app with the django cgi-handler pip install django-cgi Changed the settings.py for deployment (secret key settings, allowed host settings, debug = false) Read deployment guides and official documentation SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '6ps8j!crjgrxt34cqbqn7x&b3y%(fny8k8nh21+qa)%ws3fh!q') # SECURITY WARNING: don't run with debug turned on in production! #DEBUG = True DEBUG = os.environ.get('DJANGO_DEBUG', '') != 'False' ALLOWED_HOSTS = ['*'] I did … -
Django datefield in a model form is generated in html with type=text rather than type=date
here is my forms.py: from django import forms from django.forms import DateTimeInput, DateInput from property.models import PropertyView class DetailForm(forms.ModelForm): class Meta: model = PropertyView datepurchased = forms.DateField(input_formats=['%d/%m/%Y']) fields = ['address1', 'address2','postcode','datepurchased'] and here is how the form appears: form with text instead of date input -
djstripe not adding API keys to database from settings.py
I am new to stripe/djstripe but I am having an issue with the most basic step (installation steps). Following the djstripe documentation (https://docs.dj-stripe.dev/en/master/installation/) I am not getting expected results. What I am getting is a warning message stating I do not have API keys in the database. All I am trying to accomplish is setup a basic project to learn and test stripe payments. Below is how my stripe keys are defined in settings.py, and also the warning message I get after running "python manage.py djstripe_sync_models". If I login into django admin and add the keys manually the warning goes away, and everything seems to sync up fine. I just want to know why it is not adding the keys from my settings file. There is no mention of needing to add them manually so I assume I have something wrong. Also, I have djstripe included in "INSTALLED_APPS" and also have djstripe added to urls.py as documentation shows. settings.py # stripe/djstripe settings STRIPE_LIVE_SECRET_KEY = os.environ.get('STRIPE_SECRET_KEY') STRIPE_TEST_SECRET_KEY = os.environ.get('STRIPE_TEST_SECRET_KEY') STRIPE_LIVE_MODE = False # Change to True in production DJSTRIPE_WEBHOOK_SECRET = 'whsec_xxx' DJSTRIPE_USE_NATIVE_JSONFIELD = True DJSTRIPE_FOREIGN_KEY_TO_FIELD = "id" warning message INFOS: ?: (djstripe.I001) You don't have any API Keys in the database. … -
How to change language in a Django+Selenium test?
Why would Selenium not work with multiple languages? I'm trying to write a Selenium test for a multi-language Django app. Everything works, until I try to change the user's language. I have a /set-language/ path, which calls: @login_required def set_language(request): lang = request.GET.get('l', 'en') request.session[settings.LANGUAGE_SESSION_KEY] = lang response = HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang) return response I have Django's internationalization support to pull the language from this session variable. It works perfectly in the dev server. However, when I call it in a Selenium test with: driver.get('/set-language/?l=ja') Selenium throws the error: Traceback (most recent call last): File "/usr/local/myproject/.env/lib/python3.11/site-packages/django/test/utils.py", line 461, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/myproject/src/tests/test_lang.py", line 44, in test_language driver.get(reverse('set_language') + '?l=ja') File "/usr/local/myproject/.env/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py", line 353, in get self.execute(Command.GET, {"url": url}) File "/usr/local/myproject/.env/lib/python3.11/site-packages/selenium/webdriver/remote/webdriver.py", line 344, in execute self.error_handler.check_response(response) File "/usr/local/myproject/.env/lib/python3.11/site-packages/selenium/webdriver/remote/errorhandler.py", line 229, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=connectionFailure&u=https%3A//localhost/admin/&c=UTF-8&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20server%20at%20localhost. Stacktrace: WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:186:5 UnknownError@chrome://remote/content/shared/webdriver/Errors.jsm:513:5 checkReadyState@chrome://remote/content/marionette/navigate.js:65:24 onNavigation@chrome://remote/content/marionette/navigate.js:333:39 emit@resource://gre/modules/EventEmitter.jsm:160:20 receiveMessage@chrome://remote/content/marionette/actors/MarionetteEventsParent.jsm:44:25 and the browser is unable to bring up the page. Does Selenium not support any languages besides English? -
No Employee matches the given query
basically i am make django app with sql server ,basically i am just performing CRUD .This code is showing my all columns which are store in sql serve and also i can insert new data but when i want to update or delete data from sql server it show me error "No Employee matches the given query" even employ is exsist in database, here is the code. db_config.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'items', 'USER': 'dbuser', 'PASSWORD': 'pass', 'HOST': 'myserver', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } sql_server.py # db_server.py import pyodbc from db_config import DATABASES def get_connection(): db_config = DATABASES['default'] conn_str = ( f"DRIVER={{{db_config['OPTIONS']['driver']}}};" f"SERVER={db_config['HOST']};" f"DATABASE={db_config['NAME']};" f"UID={db_config['USER']};" f"PWD={db_config['PASSWORD']};" ) return pyodbc.connect(conn_str) project urls.py from django.contrib import admin from sqlapp import views from django.urls import include, path urlpatterns = [ path('employees/', include('sqlapp.urls')), ] app models.py from django.db import models class Employee(models.Model): EmployeeID = models.IntegerField(primary_key=True) FirstName = models.CharField(max_length=50) LastName = models.CharField(max_length=50) app urls.py from django.urls import path from . import views urlpatterns = [ path('', views.employee_list, name='employee_list'), path('create/', views.employee_create, name='employee_create'), path('<int:employee_id>/update/', views.employee_update, name='employee_update'), path('delete/<int:employee_id>/', views.employee_delete, name='employee_delete'), ] views.py from django.views.decorators.csrf import csrf_protect from django.shortcuts import render, redirect, get_object_or_404 from .models import … -
Django function to validate a Supplier's payment
I want to know if my Django view code is code more concise, readable, and optimized by using transaction. My function is to retrieve a payment and the supplier linked to this payment. Then it must update the total amount paid for the supplier, then update the supplier's balance. And all this so that if any part of the code fails, the whole operation is cancelled. @transaction.atomic() def validate_payment_supplier(request, pk): """ Function to update a Product :param request: :param pk: :return: """ try: # Get payment payment = PaymentSupplier.objects.select_for_update().get(pk=pk) # Get supplier supplier = Supplier.objects.select_for_update().get(pk=payment.supplier.id) with transaction.atomic(): # Update supplier's total payment by using the function (F) supplier.total_payment = F('total_payment') + payment.amount # Update supplier's balance by using the function (F) after updating the total payment supplier.balance = F('total_purchase') - F('total_payment') # change payment's state to validated payment.payment_supplier_to_validate(by=request.user) payment.save() supplier.save() return JsonResponse({"message": "Succès"}, status=status.HTTP_200_OK, safe=True) except PaymentSupplier.DoesNotExist: return JsonResponse({'message': 'Le paiement n\'existe pas'}, status=status.HTTP_404_NOT_FOUND) except Supplier.DoesNotExist: return JsonResponse({'message': 'Le fournisseur n\'existe pas'}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return JsonResponse({"message": str(e)}, status=status.HTTP_400_BAD_REQUEST, safe=False) I want to know if my Django view code is code more concise, readable, and optimized by using transaction. I need to get best practice. -
cannot access local variable 'form' where it is not associated with a value error
So I am writing this django website and only today did this error start to come up in one of the views. Here is the view in word: def new_ingredient(request, recipe_id): """ "Add a new entry for a particular recipe""" recipe = Recipe.objects.get(id=recipe_id) if request.method == "POST": # POST data submitted; process data form = EntryForm(data=request.POST) if form.is_valid(): new_ingredient = form.save(commit=False) new_ingredient.owner = recipe new_ingredient.save() return redirect("recipe_book:recipe", recipe_id=recipe_id) # Display a blank or invalid form context = {"recipe": recipe, "form": form} return render(request, "recipe_book/new_ingredient.xhtml", context) This is my model: class Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) text = models.TextField() time_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = "ingredients" def __str__(self): return f"{self.text[:50]}..." This is my form: class EntryForm(forms.ModelForm): class Meta: model = Ingredient fields = ["text"] labels = {"text": ""} widgets = {"text": forms.Textarea(attrs={"cols": 8})} Any help would be greatly appreciated. Thank you, Ylli. I have tried this code before and no errors occurred, but today it started to put this error up and I have no idea why it is happening. I wasn't expecting any error to come up in this view so it's a great shocker that it did. -
Django self.model.DoesNotExis
I have a user with a field set as None: None|Default User|07/07/2023 However, Django for some reason does not see it: queryset=Q(id=UUID(User.objects.get(user_id=None) ... raise self.model.DoesNotExist(pages.models.User.DoesNotExist: User matching query does not exist The closing parentheses are present. Setting the default field as another UUID present in the database as well isn't of any help. I am trying to run the migrations. My models: class User(models.Model): """ A class presenting user who can view lessons and have access to them """ user_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, null=True ) name = models.CharField(max_length=60, default='Name') date_of_registration = models.TimeField(default=timezone.now) def __str__(self): return self.id Setting the default to a present user_id doesn't help as well. Similar questions on stackoverflow were left without answers, no information about this particular problem in the Internet was found. What additional information should I provide? -
Insert data to sql databse using python django
I am trying to insert the form data to sql database. Can someone please check my code and help to find the error. def signup(request): print("Signup Started ") if request.method == 'POST': cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=PANKAJ\SQLEXPRESS;DATABASE=student_records') print("Database Object :- ",cnxn) #username = request.POST.get('username') #email = request.POST.get('email') cursor = cnxn.cursor() data = request.POST for key,value in data.items(): if key == 'username': name = value if key == 'email': email = value print('Username = ',name) print('Email = ',email) c ="insert into student values('{nm}','{em}')".format(nm=name,em=email) cursor.execute(c) cnxn.commit print("Data inserted sucessfully") return render (request,'signup.html') -
Can I see online users in Django using middleware?
I am making a website to learn Django and I am trying to make it possible to check who is online right now. I managed to do it using cookies, but I also have a desktop app that connects to the server and you can log in there as well, so users from the app were not shown as online. I saw a solution using sessions, so I might end up using it, but I have been learning about middleware and I am wondering if it would be possible to add a field to user model (last_activity) that would be updated by middleware everytime user sends a request to the server (so every time they go anywhere on the website). Then I would add a cut off time (5 minutes or something), and display it on a home page. The only issue is I am not good with middleware yet, and chatGPT suggested this: class ActivityMiddleware: def init(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if request.user.is_authenticated: user = get_user(request) user.last_activity = datetime.now() user.save() return response But it only updates on logging in, do you know how to change it to update on any request? Thanks! Trying … -
Django objects.all() return empty queryset
I have a sqlite3 database that has pre-existing data(name, price, url, img,...). When i tried to print the value from objects.all() it return <QuerySet []> and loop through the list in templates return nothing My models class Product(models.Model): name = models.CharField(max_length=200) current_price = models.CharField(max_length=50) place = models.CharField(max_length=50) url = models.CharField(max_length=50) img = models.CharField(max_length=50) date_add = models.DateTimeField(default=timezone.now) def __str__(self): return self.name My urls: path("database", views.show_db, name="show_db") My views: def show_db(request): product_list = Product.objects.all() return render(request, 'product_list.html', {'product_list' : product_list}) My templates: {% block content %} {% for product in product_list %} <li> {{product.name}} </li> {% endfor %} {% endblock %} When i use dbshell to check, there is a scrape_product table(scrape is the name of the app): CREATE TABLE IF NOT EXISTS "scrape_product"( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "name" varchar(200) NOT NULL, "current_price" varchar(50) NOT NULL, "place" varchar(50) NOT NULL, "url" varchar(50) NOT NULL, "img" varchar(50) NOT NULL, "date_add" datetime NOT NULL ); -
How to filter nested fields in a JSONField using Django ORM with Djongo?
I am working on a Django project where I am using Djongo as an ORM for MongoDB. I have a model named ProcessIDs which contains a JSONField named data. Within this JSONField, there are nested fields, and I am trying to filter the model entities based on a nested field value. Specifically, I am looking to filter based on the value of data->redirect_ids->status. I attempted to use the following query to filter the model entities: active_processes = ProcessIDs.objects.filter(data__redirect_ids__status__exact='active') I was expecting this query to return all ProcessIDs objects where the status field under redirect_ids nested within the data field is set to 'active'. However, executing this query resulted in a FieldError with the following message: FieldError: Unsupported lookup ‘redirect_ids’ for JSONField or join on the field not permitted. I am looking for a way to achieve the desired filtering using Django ORM with Djongo. Is there a specific syntax or method to filter based on nested field values within a JSONField in this setup? from djongo import models as mongo_models class ProcessIDs(mongo_models.Model): data = mongo_models.JSONField(max_length=1000, default=dict()) # ... other fields ... # Example object creation process = ProcessIDs.objects.create( data={'redirect_ids': {'ids': ['1234567', '7654321'], 'status': 'active'}, "category_type": "custom"} ) # Attempted query … -
Adding to cart Django
I'm trying to create a ecom website by Django and add products to cart, but when I run it didn't work. Can anyone help me? The codes goes here: models.py class Product(models.Model): category = models.ManyToManyField(Category, related_name='product', null=True) name = models.CharField(max_length=200, null=True) image = models.ImageField(upload_to="media", null=True) price = models.FloatField() quantity = models.IntegerField(default=0, null=True, blank=True) detail = models.TextField(max_length=1000, blank=False) digital = models.BooleanField(default=False, null=True, blank=False) def __str__(self): return self.name def get_absolute_url(self): return reverse("ecoshop:detail", kwargs={"pk": self.pk}) def get_add_to_cart_url(self): return reverse("ecoshop:add-to-cart", kwargs={"pk": self.pk}) def get_remove_from_cart_url(self): return reverse("ecoshop:remove-from-cart", kwargs={"pk": self.pk}) views.py def addtocart(request, pk): product = get_object_or_404(Product, pk=pk) order_item, created = OrderItem.objects.get_or_create(product=product, customer=request.user, order = False) order_qs = Order.objects.filter(customer=request.user, complete = False) if order_qs.exists(): order = order_qs[0] if order.items.filter(product__pk = product.pk).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "Added quantity Item") return redirect("shop:cart", pk=pk) else: order.items.add(order_item) messages.info(request, "Item added to your cart") return redirect("shop:cart", pk=pk) else: date_order = timezone.now() order = Order.objects.create(customer=request.user, date_order=date_order) order.items.add(order_item) messages.info(request, "Item added to your cart") return redirect("shop:cart", pk=pk) def cart(request): if request.user.is_authenticated: customer = request.user order, created = Order.objects.get_or_create(customer = customer, complete = False) cartItem = order.get_cart_items items = order.orderitem_set.all() else: items = [] order = {'get_cart_items': 0, 'get_cart_total': 0} cartItem = order['get_cart_items'] categories = Category.objects.filter(is_sub=False) if request.user.is_authenticated: customer = request.user order, created … -
Django 4.2.5 System check identified no issues (0 silenced)
After reinstalled my app on another computer Want to change Python Version and update if necessary Librairies Eveything is ok for now (I had some issue with xhtmltopdf librairies with python 3.10 and more so for now I'm using 3.9 Python version) I run manage.py runserver ... But I've only got this message System check identified no issues (0 silenced). I tried to run with -v manage.py to have some details .. Nothing wrong on details I see some user who have this kind of issue and modify the 3306 port for mysql ... I did but still the same message. Is there any other solution ? Thanks for your help -
Remover link malicioso no site, encontrados pela Google Ads
Tenho um site, que desenvolvi com Django (python), html, css e javascript, hospedado no servidor pythonanywhere Ao tentar criar campanhas de anúncio no Google Ads com esse site, eles estão reprovando um anúncio por "software malicioso" Ao questionar a Google, ela respondeu que 3 links estão no site, e redirecionando os visitantes Links maliciosos: Https://betwinner1.com/pwapp Https://odnaknopka.ru/ Https://powered-by-revidy.com/ Porém eu já fiz diversas varreduras, e não encontrei nenhum desses links de redirecionando Onde no meu site, é possível esses links estarem sendo detectados pelo algoritmo da Google Ads, e como remover? Já procurei nos arquivos html, css e javascript, porém não encontrei esses links Não sei se a pythonanywhere é uma plataforma de hospedagem frágil Segue uma imagem com a resposta da Google Ads, explicando o porque reprova o site e os links maliciosos enter image description here -
Django product variation model - how to get distinct color
I am building a ecommerse store with django. One of the requirement is that a product can have a color and different sizes. I also want to keep track of the quantity of each size. I can create ProductVariation like product='test', size='small', color='red', quantity=5 , product='test', size='large', color='red', quantity=10. Now in db there are two objects created,how can I query that I only get color red in queryset when I am rendering product details. I looked at this example - Django Products model for e-commerce site but did not understand this bit - Color.objects.filter(productvariant__product=some_product).distinct() These are my models: class Product(models.Model): """ Product model to allow creating product records and linking with category """ product_uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) product_name = models.CharField(max_length=255) sub_category = models.ForeignKey( 'SubCategory', on_delete=models.CASCADE, related_name='products') product_description = models.TextField() is_featured = models.BooleanField(default=False) product_sku = models.CharField(max_length=255, null=True, blank=True) product_price = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.product_name class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' class ProductVariation(models.Model): """ ProductVariation model to allow creating product with different size and color """ product_var_uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) product = models.ForeignKey( 'Product', on_delete=models.CASCADE, related_name='product_variations') size = models.ForeignKey('Size', on_delete=models.CASCADE, related_name="product_sizes") color = models.ForeignKey('Color', on_delete=models.CASCADE, related_name="color") quantity = models .IntegerField() def __str__(self): return self.product.product_name … -
.ebextensions folder not included in my eb deploy method
The configuration for my static files in my django project are contained in my .ebextensions folder but during the deployment process it seems the folder is not being added to the EB environment. As a result my web app is not serving any static files when running from my ec2 instance. I've set up environment properties to include aws:elasticbeanstalk:environment:proxy:staticfiles in my elastic beanstalk configuration. I've checked to ensure my .ebextensions folder exists in my github. For some reason during deployment to EB the folder is being deleted / ignored. -
Django Mptt: filtering based on child category
I use django-mptt for Category model and I have Service model as well. The problem: I got all services associated to node category by clicking on a child category. What I want: I want to get all services associated to child category that I click. I believe I have to check it in an additional step in views (ServiceByCategoryListView). But I have no idea how to do that. Google doesn’t help me. models.py class Service(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(max_length=255) description = models.TextField() preparation = models.TextField() price = models.CharField(max_length=10) available = models.BooleanField(default='True') category = TreeForeignKey('Category', on_delete=models.PROTECT, related_name='services') def __str__(self): return self.name class Category(MPTTModel): name = models.CharField(max_length=255, unique=True) parent = TreeForeignKey('self', on_delete=models.PROTECT, null=True, blank=True, related_name='children', db_index=True) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = [['parent', 'slug']] def get_absolute_url(self): return reverse('services-by-category', kwargs={'slug': self.slug}) urls.py urlpatterns = [ path('', CategoryListView.as_view(), name='category-list'), path('<slug:slug>/', ServiceByCategoryListView.as_view(), name='services-by-category'), ] views.py class CategoryListView(ListView): model = Category template_name = 'main/category_list.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['services'] = Service.objects.all() return context class ServiceByCategoryListView(ListView): model = Service context_object_name = 'services' template_name = 'main/service_list.html' def get_queryset(self): self.category = Category.objects.filter(parent=None).get(slug=self.kwargs['slug']) branch_categories = self.category.get_descendants(include_self=True) queryset = Service.objects.filter(category__in=branch_categories) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['name'] = self.category … -
The correct value is not saved in the database when I create an object in a Django project
I am writing a basic Django CRM project that is shared among organizations. When the superuser creates a new organization, he must set an organization name, organization owner and organization admin team. I am also attaching the relevant code: organization models.py class Organization(models.Model): name = models.CharField( max_length=255, unique=True, ) owner = models.OneToOneField( User, on_delete=models.CASCADE ) members = models.ManyToManyField( User, related_name='organizations', ) created_at = models.DateTimeField( auto_now_add=True ) updated_at = models.DateTimeField( auto_now=True ) def __str__(self): return self.name team models.py class Team(models.Model): name = models.CharField( max_length=255 ) created_by = models.ForeignKey( User, related_name='created_by', on_delete=models.CASCADE, ) organization = models.ForeignKey( Organization, on_delete=models.CASCADE ) created_at = models.DateTimeField( auto_now_add=True ) updated_at = models.DateTimeField( auto_now=True ) def __str__(self): return self.name user models.py class User(AbstractUser): username = None email = models.EmailField( _("email address"), unique=True, validators=[ validators.EmailValidator(), ] ) team = models.ForeignKey( 'team.Team', related_name='agents', null=True, blank=True, on_delete=models.CASCADE ) is_agent = models.BooleanField(default=True) is_org_owner = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Meta: verbose_name = 'CRM User' verbose_name_plural = 'CRM Users' view.py @login_required @superuser_access def add_organization(request): if request.method == 'GET': user_form = AddOrgOwnerForm() organization_form = AddOrganizationForm() team_form = AddTeamForm() else: user_form = AddOrgOwnerForm(request.POST) organization_form = AddOrganizationForm(request.POST) team_form = AddTeamForm(request.POST) if user_form.is_valid() and organization_form.is_valid() and team_form.is_valid(): …