Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
OSError: [WinError 127] after gdal installation
I have just finished installing gdal 3.6 on Windows, and it looks like my django project is getting the file correctly. But when I run django manage.py check, it gives me the following output: File "C:\users\rodri\dev\mymap\.mymap\Lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 69, in <module> lgdal = CDLL(lib_path) ^^^^^^^^^^^^^^ File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.752.0_x64__qbz5n2kfra8p0\Lib\ctypes\__init__.py", line 379, in __init__ self._handle = _dlopen(self._name, mode) ^^^^^^^^^^^^^^^^^^^^^^^^^ OSError: [WinError 127] Não foi possível encontrar o procedimento especificado Did someone already get through it, or knows how to fix it? -
why am I not able to pass token correctly in my Djano views?
I have below code class ProxyAPI(CreateAPIView): serializer_class = DummySerializer def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.org = None self.ent = None self.linkde = None def post(self, request, *args, **kwargs): org = request.data.get("org") ent = request.data.get("ent") erpid = request.data.get("erpid") self.org = org self.ent = ent self.erpid = erpid combined_response = [] post_api_views = [ abc, xyz ] linkdetl = self.get_queryset() if not linkdetl: return Response("Link token not found.", status=status.HTTP_404_NOT_FOUND) token = linkdetl[0] for index, api_view_class in enumerate(post_api_views, start=1): try: api_instance = api_view_class(token) response = api_instance.post(request) if response.status_code == status.HTTP_200_OK: return Response("success") except Exception as e: error_message = f"Anddd error occurred while calling API {index}: {str(e)}" return Response({'error': error_message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) return Response(combined_response, status=status.HTTP_200_OK) class Info(APIView): token = None # def __init__(self): # self.token = token # super().__init__() # @staticmethod def get_info(self): comp_client = create_client(self.token) print(comp_client) try: organization_data = comp_client.accounting.company_info.list(expand=something) return organization_data except Exception as e: api_log( msg=f"Error retrieving organizations details: {str(e)} \ - Status Code: {status.HTTP_500_INTERNAL_SERVER_ERROR}: {traceback.format_exc()}") def get(self, request, *args, **kwargs): organization_data = self.get_info() formatted_data = self.build_response_payload(organization_data) return Response(formatted_data, status=status.HTTP_200_OK) class abc(APIView): token = None # def __init__(self): # self.token = token # super().__init__() @staticmethod def post(request): authorization_header = request.headers.get('Authorization') if authorization_header and authorization_header.startswith('Bearer '): token = authorization_header.split(' ')[1] token = … -
Django CSS not loading even though configuration is set correctly
I linked my static files to base.html in my Django app my index.html is inheriting from my base.html I linked my css file to my base.html so all other html files will inherit from it I have configured all settings but anytime I runserver my css doesn't load, it used to work before then it just suddenly stopped working This is how my html loads Please I need a fix -
Getting total count of the iteration in multiple for loops: django template
I am working on a project using django I have 2 lists classes and students I need to iterate in these and print the s.no , class.name and class.student.name using django template the code snippets looks something like: {% for class in classes %} {% for student in class.students %} <tr> <td>#{{ count }}</td> <td>{{ student.name }}</td> <td>{{ class.name }}</td> </tr> {% endfor %} {% endfor %} I am not able to get the correct count as we have either the parentloop counter of for loop counter but i need the count of total iteration i tried something like {% with count=0 %} {% for class in classes %} {% for student in class.students %} {% with count=count|add:1 %} <tr> <td>#{{ count }}</td> <td>{{ student.name }}</td> <td>{{ class.name }}</td> </tr> {% endwith %} {% endwith %} {% endfor %} {% endfor %} but this always give the count as 1 changing the position of the for loop also did not worked. Do we have a solution to this? Regards -
axios django 403 (forbidden): CSRF Failed: CSRF token missing
I have a Django-React Project. I can't POST or PUT APIs from the front; I get a 403 forbidden error every time I make a request, only works when I request from the back. I keep getting the same 'CSRF Failed: CSRF token missing.' message. It was working before completely until I ran 'npm i' to update dependencies that were missing. After that, everything broke. So I'm pretty certain my code is correct since it was working before, does anyone know if any node dependencies break stuff? There is csrftoken being generated under request headers cookies, not sure what would cause the issue. This is how I am declaring my axios on the front: constructor() { // Necessary Credentials axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; axios.defaults.withCredentials = true; // Establish Axios Client this.client = axios.create({ baseURL : "http://127.0.0.1:8000" }); }; This is some of my settings.py that may be helpful: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'API.apps.UserApiConfig' ] 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', 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://127.0.0.1:3000', ] CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:3000'] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), } Tried … -
I have a view issue in django the file is not working properly
File "C:\Users\Zeeshan Alvi ( BUH )\Desktop\Python\Webitewithdjango\ebookbackend\ebookbackend\urls.py", line 26, in path('login/', views.login_view, name='login'), # Corrected URL pattern for login ^^^^^^^^^^^^^^^^ AttributeError: module 'myapp.views' has no attribute 'login_view' I make my website fronted complete using HTML , CSS & Java Script . I also connect my contact page to my database and also get data , but I did a mistake a make a backend using a single file index.html only after I try to connect my login page with my database but it gives some error and that of my backend of contact page is also ruined and right now I try for many hours but cant fix the bug. Is there anyone to help me. I need a person some to have a chat with him/her to discuss it . -
Django ALLOWED_HOSTS not changing
I have a django app hosted on a DO linux droplet running nginx and gunicorn. I am trying to point the domain to the IP. But I get the below error when I try to open the webapp in browser DisallowedHost at / Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS. Request Method: GET Request URL: http://example.com/ Django Version: 4.2.1 Exception Type: DisallowedHost Exception Value: Invalid HTTP_HOST header: 'example.com'. You may need to add 'example.com' to ALLOWED_HOSTS. But in my settings.py, I already have the domain added as below (x.x.x.x is the IP): ALLOWED_HOSTS = ['x.x.x.x' ,'example.com', 'www.example.com'] In the error message in browser, when I look at local vars allowed_host, I can only see the IP (which was the earlier setting before I added the domain): Variable Value allowed_hosts ['x.x.x.x'] domain 'example.com' host 'example.com' msg ("Invalid HTTP_HOST header: 'example.com'. You may need to add " "'example.com' to ALLOWED_HOSTS.") port '' self <WSGIRequest: GET '/'> I restarted the gunicorn but still nothing changes. sudo systemctl restart gunicorn Why is the change in allowed_hosts not reflecting ? -
How to default the external link tab in RichTextBlock link modal in Wagtail admin?
I'm using Wagtail CMS and noticed that when I try to add a link in a RichTextBlock in the Wagtail admin interface, the link modal defaults to the internal link tab. However, I want it to default to the external link tab instead. I've explored some of the Wagtail source code and found client/src/entrypoints/admin/page-chooser-modal.js, which seems to handle the switching of tabs in the link modal. However, I'm unsure how to modify this to make the external link tab the default. I've also looked at the templates wagtailadmin/chooser/_link_types.html and wagtailadmin/chooser/browse.html. It seems like browse.html renders content for internal links by default. While I could potentially modify this template to render external links, it seems like the data for external links needs to be passed from a view, so simply changing the template might not be sufficient. Am I looking in the right places to achieve this customization? If not, where should I be looking, and how can I default the link modal to the external link tab? -
Used 1 item in Ajax
don't be tired I wrote a program to register the user, for example, the user came and made a mistake in both passwords, show the error using Ajax, of course, it will only happen once, and if the password is wrong again, the error will not show up, which means it will be used only once. Infinite use in Ajax, of course, the page does not load -
Django User View Affects current_user
I have url for viewing all info about specific user: blog/urls.py urlpatterns += path('user/<int:pk>/', UserDetailView.as_view(), name='user-detail'), that uses this UserDetailView View: blog/views.py class UserDetailView(DetailView): model = User template_name = 'blog/user_detail.html' that inherits from DetailView and uses Django's User model. I have navbar in base html file that displays current user nickname with link to their page attached to it: base.html(which all other html files inherit from)``` {% if user.is_authenticated %} New Post {{ user.username }} Logout Now, when I'm logged in and looking any page except `'user/<int:pk>/'`, nickname with link shows as it should, but when I'm looking some specific user's page, {{ user ]} changes from current user to user who's page I'm looking at: [images](https://imgur.com/a/0tWKXQg). ListView with Post model that calls User by its nickname does not affect current user: blog/urls.py urlpatterns += path('user/str:username', UserPostListView.as_view(), name='user-posts') blog/views.py class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # /_.html # blog/post_list.html context_object_name = 'posts' paginate_by = 2 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') ['user/<str:username>'](https://i.stack.imgur.com/6XM4a.png). Is there a way for me to prevent DetailView with User model from changing {{ user }} from current user to one who's page I'm looking at? -
Can't connect to Grafana via running via docker-compose
I recently started to get into docker. I am coding an application using Django 5.0.2 and want to add Dashboard from grafana and prometheus. Prometheus works, but i can't seem to be able to connect to grafana via localhost:3050 (3000 was already taken) here is my docker-compose.yml file: version: '3.8' services: prometheus: image: prom/prometheus:latest ports: - "9090:9090" # This example maps host port 8080 to container port 9090 (Prometheus default) volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml:ro grafana: image: grafana/grafana environment: GF_INSTALL_PLUGINS: "grafana-clock-panel,grafana-simple-json-datasource" restart: 'no' volumes: - grafana_data:/var/lib/grafana ports: - 3050:3050 depends_on: - prometheus network_mode: bridge volumes: prometheus_data: {} grafana_data: {} prometheus.yml: # my global config global: scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute. evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute. # scrape_timeout is set to the global default (10s). # Alertmanager configuration alerting: alertmanagers: - static_configs: - targets: # - alertmanager:9093 # Load rules once and periodically evaluate them according to the global 'evaluation_interval'. rule_files: # - "first_rules.yml" # - "second_rules.yml" # A scrape configuration containing exactly one endpoint to scrape: # Here it's Prometheus itself. scrape_configs: # The job name is added as a label `job=<job_name>` … -
How the Session works in browsers
I have this Django code which get the "msg" from the session and save it to a variable msg then check if the msg is true if true it will delete it from the session but still the msg variable contains the old value. I know i can set the msg to False in the if block but is there another way of doing this def get(self, request): msg = request.session.get("msg", False) if msg: del request.session["msg"] context = {"message": msg} return render(request, "guess_form.html", context) def post(self, request): guess = request.POST.get("guess") msg = checkGuess(guess) request.session["msg"] = msg return redirect(request.path) I Want to make the msg to be empty when the app runs for the first time the msg meaning the variable -
Nested objects in Django REST Framework when a field is required for POST and not for DELETE
I'm using serializers while dealing with nested objects. Similar to the example by Django REST framework I have: class UserSerializer(serializers.Serializer): email = serializers.EmailField(required=True) #Not required for POST (see following) username = serializers.CharField(max_length=100, required=True) #Not required for DELETE (see following) class PostCommentSerializer(serializers.Serializer): user = UserSerializer(required=True) class DeleteCommentSerializer(serializers.Serializer): user = UserSerializer(required=True) I'm in a situation where I want only username to be required (validated) when PostCommentSerializer is used, and only email to be required when DeleteCommentSerializer is used. What options do I have? in my current setting, both email and username are required for both POST and DELETE. -
Rending a separate page dynamically using django and htmx
Am working on a simple task app using Django and HTMX. I want when a user clicks on a button in the navbar to add a task, the add task page should be displayed dynamically without causing a page reload. Yes the task page gets displayed dynamically but when i try to reload my page Some content of the page gets lost. Checkout below the code snippets navbar.html {% load static %} <div class="flex justify-between pt-10 pb-3"> <div class="w-6/12"> <div class="font-bold text-gray-700 text-2xl" style="cursor: pointer;">Task Manager</div> </div> <div class="w-1/12 text-gray-500" style="cursor: pointer;">Home</div> <div class="w-1/12 text-gray-500" style="cursor: pointer;">Pending</div> <div class="w-1/12 text-gray-500" style="cursor: pointer;">Complete</div> <div class="w-1/12 text-gray-500" style="cursor: pointer;">Pricing</div> <div class="w-1/12 text-gray-500"> <div class="flex justify-center items-center"> <a role="button" class="bg-blue-700 rounded text-white font-bold text-sm px-4 py-1" href="{% url "create_todo" %}" hx-get="{% url "create_todo" %}" hx-push-url="true" hx-target="#main">Add Task</a> </div> </div> <div class="w-1/12 text-gray-500"> <div class="flex justify-center items-center"> <img src="{% static 'images/me.jpg' %}" alt="Profile" srcset="" class="rounded-full w-12 h-12"> </div> </div> </div> <hr> home.html {% extends "../base.html" %} {% block title %}Home Board{% endblock title %} {% block content %} {% include "./navbar.html" %} <div class="px-20" id="main"> <div class="flex justify-between"> <h3 class="mt-5 text-center text-xl text-gray-500 font-bold my-8">Today's Tasks</h3> <div class="flex justify-center items-center"> <button class="bg-blue-700 rounded text-white … -
Django 5.1 models with fields using db_default throw on full_clean
Trying to implement Django 5's new db_default attribute for fields Using the following field as an example: editable = models.BooleanField(db_default=True) Would expect that if editable not specified when creating a new instance, that ORM would not throw error but would still save instance, and that the value of editable would be set to True at the database level. So executing the following to create a new object: product_obj = models.Product( id=id, name=name, is_active=is_active, inventory_type=inventory_type, leadtime=leadtime, ) product_obj.full_clean() product_obj.save() would be expected to succeed. Instead full_clean() raises a ValidationError: django.core.exceptions.ValidationError: {'editable': ['“<django.db.models.expressions.DatabaseDefault object at 0x151db1c70>” value must be either True or False.']} and similar behavior occurs throughout my codebase for any field for which db_default is set (CharField with choices, IntegerField, etc) Clearly I'm not understanding how db_default should be used. -
Read JSON Data from an incoming Django Request and Displaying the Data to HTML
I'm a month old of using Django and I want to create a Registration Form where the data will came from a POST Request (from a microreader that will throw a JSON data going to the Django View Endpoint). Once I received the response, I need to get the data_id and the user must input the name and its department, and displaying it as a form in the HTML that will be pushed to my database, once submitted. However, I'm having a hard time crafting this thing in views.py and its template. This is the thrown JSON Response: {"station":"XXXXXXXX","type":"TYPE-XXX","data_id":"9198491920"} This is the views.py @csrf_exempt def registration_form(request): if request.method == "POST": # Process the JSON data json_data = json.loads(request.body) dataid = json_data.get('data_id') # Initialize the form with the received dataid form = RegistrationForm(initial={'data_id': dataid) if form.is_valid(): name = form.cleaned_data['name'] department = form.cleaned_data['department'] return render(request,'registration.html',{'form':form}) else: # If GET request, initialize form form = RegistrationForm() return render(request, 'registration.html', {'form': form}) This is my registration.html. Although, you may not expect some things in my HTML since I'm trying all forms of displaying but there's no success. {% extends 'base.html' %} {% load static %} {% load widget_tweaks %} {% block content %} <form … -
Django i18n get_language_info_list and get_available_languages provide different language code
With {% get_current_language as CURRENT_LANGUAGE %} , {{ CURRENT_LANGUAGE }} shows nl-nl With {% get_available_languages as AVAILABLE_LANGUAGES %} , {{ AVAILABLE_LANGUAGES }} shows [('nl-NL', 'Nederlands'), ('en', 'Engels')] With {% get_language_info_list for AVAILABLE_LANGUAGES as LANGUAGES %} , {{ LANGUAGES }} shows [{'bidi': False, 'code': 'nl', 'name': 'Dutch', 'name_local': 'Nederlands', 'name_translated': 'Nederlands'}, {'bidi': False, 'code': 'en', 'name': 'English', 'name_local': 'English', 'name_translated': 'Engels'}] Settings: # https://docs.djangoproject.com/en/dev/ref/settings/#language-code LANGUAGE_CODE = "nl-NL" # https://docs.djangoproject.com/en/dev/ref/settings/#languages LANGUAGES = [ ('nl-NL', _('Dutch')), ('en', _('English')), ] In {{ LANGUAGES }} I expect code to be nl-NL and not nl. Anyone that can explain this discrepancy? Django version: Django==4.2.10 -
Temporal Workflow Issue in python: Response Not Returned, Queueing/Deadlock Occurs, Unable to Trigger New Workflow Unit Until Current One Finishes
I've created a workflow with 4 activity which runs one after another using temporalio, When my one workflow starts it not giving response, it is queued/Deadlock Occurs, Unable to trigger new workflow unit current one finishes. import asyncio import random import concurrent import multiprocessing from datetime import timedelta from temporalio.client import Client from temporalio.worker import Worker from temporalio import activity, workflow from temporalio.worker import SharedStateManager, Worker async def get_client(): client = await Client.connect("localhost:7233") return client @activity.defn async def activity1(params) -> dict: print("Inside activity 1") count = 1 while True: if count == 10000000000: break count = count + 1 return params @activity.defn async def activity2(params) -> dict: print("Inside activity 2") return params @activity.defn async def activity3(params) -> dict: print("Inside activity 3") return params @activity.defn async def activity4(params) -> dict: print("Inside activity 4") return params @workflow.defn class TestTemporalWorkflow: @workflow.run async def run(self, params) -> dict: response_1 = await workflow.start_activity( activity1, params, start_to_close_timeout=timedelta(seconds=100), ) response_2 = await workflow.start_activity( activity2, response_1, start_to_close_timeout=timedelta(seconds=100), ) response_3 = await workflow.start_activity( activity3, response_2, start_to_close_timeout=timedelta(seconds=100), ) response_4 = await workflow.start_activity( activity4, response_3, start_to_close_timeout=timedelta(seconds=100), ) async def main(params): task_queue = "demo-temporal-workflow-queue" workflows = [TestTemporalWorkflow] activities = [activity1, activity2, activity3, activity4] # Start client client = await get_client() async with … -
Is it possible to access a method decorator's information in Python?
I've designed a RBAC method in a Django project using the following concept: Declare an attribute permission_roles in the View/Viewset body This attribute receives information regarding the user roles that can access each method/action of the view (e.g.: 'create': (RoleChoices.ADMIN)) Then I had to think how to inform the frontend about role capabilities. I've thought of using a new model class Permission that stores an array of roles and have an unique name identifier (e.g.: Permission(action="user_management_list", roles=[1,2,3])) In order to populate this model, I've used the autodiscover Django's method + a decorator that goes above my view methods/actions: @allowed_roles('user_management_list', [RoleChoices.ADMIN]) def list(self, request, *args, **kwargs): return super().list(request, *args, **kwargs) Now I was thinking of a way to merge both functionalities, simplifying the RBAC custom permission by using the action name + the request user role and query directly to the DB (later I'll use also a cache strategy to reduce DB load). But the problem is, how could I access the decorator's first param (its the action name)? -
When I am running runserver command and the server starts and entering to the admin pannel there is an OperationalError
In models.py: # from email.policy import default # from pyexpat import model from django.db import models # from unicodedata import decimal from shortuuid.django_fields import ShortUUIDField from django.utils.html import mark_safe from userauths.models import CustomUser STATUS_CHOICE=( ("process","Processing"), ("shipped","Shipped"), ("delevered","Delevered"), ) STATUS=( ("draft","Draft"), ("disable","Disable"), ("rejected","Rejected"), ("In_review","In Review"), ("published","Published"), ) RATING=( (1,"⭐☆☆☆☆"), (2,"⭐⭐☆☆☆"), (3,"⭐⭐⭐☆☆"), (4,"⭐⭐⭐⭐☆"), (5,"⭐⭐⭐⭐⭐"), ) # Create your models here. def user_directory_path(instance,filename): return 'user_{0}/{1}'.format(instance.user.id, filename) class Category(models.Model): cid=ShortUUIDField(length=10,max_length=100,prefix="cat",alphabet="abcdef") title=models.CharField(max_length=100,default="Food") image=models.ImageField(upload_to="category",default="category.jpg") class Meta: verbose_name_plural="Categories" def catagory_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Tags(models.Model): pass class Vendor(models.Model): vid=ShortUUIDField(length=10,max_length=100,prefix="ven",alphabet="abcdef") title=models.CharField(max_length=100,default="Nest") image=models.ImageField(upload_to=user_directory_path,default="vendor.jpg") description=models.TextField(null=True, blank=True,default="Normal Vendorco") address=models.CharField(max_length=100, default="6,Dum Dum Road") contact=models.CharField(max_length=100, default="+91") chat_resp_time=models.CharField(max_length=100,default="100") shipping_on_time=models.CharField(max_length=100,default="100") authenticate_rating=models.CharField(max_length=100,default="100") days_return=models.CharField(max_length=100,default="100") warranty_period=models.CharField(max_length=100,default="100") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) class Meta: verbose_name_plural="Vendors" def Vendor_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title class Product(models.Model): pid=ShortUUIDField(length=10,max_length=100,prefix="prd",alphabet="abcdef") user=models.ForeignKey(CustomUser, on_delete=models.SET_NULL ,null=True) cagtegory=models.ForeignKey(Category, on_delete=models.SET_NULL ,null=True) title=models.CharField(max_length=100,default="Apple") image=models.ImageField(upload_to=user_directory_path,default="product.jpg") description=models.TextField(null=True, blank=True,default="This is a product") price = models.DecimalField(max_digits=10, decimal_places=2, default=1.99) old_price = models.DecimalField(max_digits=10, decimal_places=2, default=2.99) specifications=models.TextField(null=True, blank=True) tags=models.ForeignKey(Tags, on_delete=models.SET_NULL ,null=True) product_status=models.CharField(choices=STATUS, max_length=10,default="In_review") status=models.BooleanField(default=True) in_stock=models.BooleanField(default=True) featured=models.BooleanField(default=False) digital=models.BooleanField(default=False) sku=ShortUUIDField(length=10,max_length=100,prefix="sku",alphabet="abcdef") date=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(null=True,blank=True) class Meta: verbose_name_plural="Products" def product_image(self): return mark_safe('<img src="%s" width="50" height="50"/>'%(self.image.url)) def __str__(self): return self.title def get_percentage(self): new_price=(self.price/self.old_price) * 100 return new_price class ProductImages(models.Model): images=models.ImageField(upload_to="product-image",default="product.jpg") product=models.ForeignKey(Product, on_delete=models.SET_NULL ,null=True) date=models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural="Product Images" ######################################################Care,Order,CartItemsand Address########################### class CartOrder(models.Model): user=models.ForeignKey(CustomUser,on_delete=models.CASCADE) price= models.DecimalField(max_digits=10, … -
after connecting redis to django and docker, the data is not saved in redis-cli
I connected redis to django and did docker-compose, redis itself works, but if I want to connect to the terminal via docker exec -it redis redis-cli, then it connects, but I can’t get any data and if I write the keys * command, then no data either (except for celery) version: '3.8' services: web: build: . container_name: django ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app env_file: - .env environment: - DEBUG=1 - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 - REDIS_HOST=redis depends_on: - db - redis links: - db:db db: container_name: postgres image: postgres volumes: - ./data/postgres_data:/var/lib/postgresql/data environment: - POSTGRES_DB=${BD_NAME} - POSTGRES_USER=${BD_USER} - POSTGRES_PASSWORD=${BD_PASSWORD} - POSTGRES_HOST_AUTH_METHOD=trust expose: - '5432' redis: image: "redis:alpine" restart: always container_name: redis command: redis-server ports: - 6379:6379 celery: build: . command: celery -A wishes worker -l INFO volumes: - .:/app depends_on: - web - redis - db environment: - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 volumes: postgres_data: -
What is causing the route to change (ikely because form is submitting), i also added return false in the function?
I am currently building a single page web app and wanted that js handle the form submission and so that route remain the same. But when i click the submit button route changes, JS Code: document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); // By default, load the inbox load_mailbox('inbox'); }); function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; } function load_mailbox(mailbox) { // Show the mailbox and hide other views document.querySelector('#emails-view').style.display = 'block'; document.querySelector('#compose-view').style.display = 'none'; // Show the mailbox name document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`; } function send_mail(event){ const recipients = document.querySelector('#compose-recipients').value; const subject = document.querySelector('#compose-subject').value; const body = document.querySelector('#compose-body').value; //send the email as post to the server fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: recipients, subject: subject, body: body }) }) .then(response => response.json()) .then(result => { console.log(result); //loading the sent box after sending the email load_mailbox('sent'); }) return false; } document.querySelector('#compose-form').onsubmit = send_mail; HTML code: {% extends "mail/layout.html" %} {% load static %} {% block body %} … -
ImportError Django cannot import name 'SignupView'
So I imported the 'LoginView, LogoutView' but when I tried to import the 'SignupView' I got the following error: ImportError: cannot import name 'SignupView' from 'django.contrib.auth.views' (C:\Users\USER\Desktop\djang0\venv\Lib\site-packages\django\contrib\auth\views.py) This is what I believe to be the necessary code. #my views.py from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect, reverse from django.core.mail import send_mail from django.views import generic from django.http import HttpResponse from.models import Lead, Agent from.forms import LeadForm, LeadModelForm class SignupView(generic.CreateView): template_name = "registration/signup.html" form_class = UserCreationForm def get_success_url(self): return reverse("login") #my app urls.py from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.contrib.auth.views import LoginView, LogoutView, SignupView from django.urls import path, include from leads.views import hero_page, HeroPageView urlpatterns = [ path('admin/', admin.site.urls), path('', HeroPageView.as_view(), name="hero-page"), path('leads/', include('leads.urls', namespace="leads")), path('login/', LoginView.as_view(), name="login"), path('logout/', LogoutView.as_view(), name="logout"), path('signup/', SignupView.as_view(), name="signup"), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I don't know what to try, I'm kind of a beginner in Django. I've done a lot of research on multiple sites and articles but only person I've seen who had a similar problem had to remove the 'views' from the 'from django.contrib.auth.views' because they ran on an older version of Django which I believe to have been 2.0.1 but I'm … -
Python ImportError that puzzles me (already searched for similar stackoverflow posts with no luck)
I'm building an API with django ninja, for design reasons I'm using some logic inside microservice/logic/one_module.py that needs to get JSON data from microservice/service/repository.py This is my project structure: | .coveragerc | manage.py | pytest.ini | +---microservice | asgi.py | models.py | settings.py | urls.py | wsgi.py | __init__.py | +---logic | config.py | correlate.py | correlation_rules.py | generate_ticket.py | send_ticket.py | startup.py <--------- Code is being executed here | temp.py | __init__.py | | +---service | | application.py | | domain.py | | repository.py <--------- Data is here (must be imported) | | __init__.py | | | +---schemas | | application.py | | domain.py | | repository.py | | __init__.py | | | +---tests | | test_application.py | | test_domain.py | | test_logic.py | | test_repository.py | | __init__.py | | | +---json | alert_1.json | client_1.json | secrets_1.json | +---static | logo.png | script.js | styles.css | +---templates base.html email.html In service/repository.py I have: json_call = requests.get(...etc...) clients, alerts, secrets = ...comprehension to get the data as dict... In logic/startup.py I have: from microservice.service.repository import clients, secrets, alerts clients = ...some code using the data... Running it like that, it raises an error: Traceback (most recent call last): … -
Django ManyToMany not saving
I have a ModelMultipleChoiceField that I try to save save as ManyToMany relationships and tried almost every solution on the internet but for some reason I can't get mine to save. I don't get any errors and the rest of the form submits just not the ManyToMany. Models.py class Game(models.Model): players = models.ManyToManyField(Student, blank=True) other fields... class Student(models.Model): user_name = models.CharField(max_length=150, null=False, blank=False) Forms.py class Game(forms.ModelForm): players = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Student.objects.all(), label="Players", required=False) Views.py def creategame(request): if request.method == "POST": form = Game(request.POST) if form.is_valid(): form.save() return redirect(reverse('management')) else: ... I tried multiple solutions like this, but none of them worked. Views.py def creategame(request): if request.method == "POST": form = Game(request.POST) if form.is_valid(): new_game = form.save(commit=False) new_game.save() form.save_m2m() return redirect(reverse('management')) else: ...