Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Combining django-jsonform with HTMX and CrispyForms resulting in removed interactivity after submit
I am using django to create a form that uses a JSONForm field from the django-jsonform package. I am using HTMX for asyncronous submission of the form and render_crispy_form for rendering the form back after it has been submitted. However, after submitting the form, the things inside the JSONForm are not shown anymore and the interactivity is removed for the django-jsonform field part. Here is my model: class GroceryStore(models.Model): PRODUCTS_SCHEMA = { "type": "array", "items": { "type": "object", "properties": { "name": {"type": "string"}, "price": {"type": "number"}, }, "required": ["name", "price"], } } creator = models.OneToOneField(User, on_delete = models.CASCADE) name = models.CharField(max_length = 200) products = JSONField(schema = PRODUCTS_SCHEMA, null = True, blank = True, default = None) The data is saved when valid data is submitted, the problem is just that it does not reflect it on the frontend. I am using this for generating the html to replace the form using HTMX: form_html = render_crispy_form(grocery_form) return HttpResponse(form_html) It says in the documentation that HTMX is supported. What could be the problem? -
Django gunicorn setup - DJANGO_WSGI_MODULE - ModuleNotFoundError: No module named 'config'
I'm trying setup the gunicorn but I am facing an error for DJANGO_WSGI_MODULE. DJANGO_WSGI_MODULE=config.wsgi `ModuleNotFoundError: No module named 'config' File "/webapps/djangoapp/myapp_venv/lib/python3.11/site-packages/gunicorn/util.py", line 371, in import_app mod = importlib.import_module(module) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.11/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^` Configuration wsgi_app: None PS: when I run the command directly in the terminal from project root, I am not getting this error. Below command is running properly. myapp_venv/bin/gunicorn config.wsgi:application --name myapp --workers 3 --timeout 120 --user=myappapi --group=webapps --bind=unix:/webapps/myapp/run/gunicorn.sock --log-level=debug --log-file=- Can anyone help please? Thanks I tried to search for wsgi app name but it doesn't work. I also tried to run the command manually and it worked so it looks like directory path related issue. I also think that wsgi_app is set to None which can be causing the issue. I followed this YT video to set this up and have asked question there as well. https://www.youtube.com/watch?v=RIE0O0Lbk8U -
I'm using cryptography in django and the problem is "it is not decrypting the value when using "from_db_value" function"
settings.py: ENCRYPTION_KEY=b'iHHJ-OlINvt7Ez7-js9JiAAy2I_hFJXWYhi8yIJZPCs=' models.py: from django.db import models from .fields import EncryptedTextField class all_License(models.Model): Lic_Id= models.IntegerField(primary_key=True, auto_created=True) LicenseKey= EncryptedTextField() ProductID= models.ForeignKey(Products, on_delete=models.CASCADE) ClientID= models.ForeignKey(Clients, on_delete=models.CASCADE) ActivationStatus= models.BooleanField() ExpirationDate= models.DateField() IssuedDate= models.DateField() AssociatedDeviceID= models.IntegerField() AdditionalText= models.TextField() fields.py: from cryptography.fernet import Fernet, InvalidToken from django.db import models from django.conf import settings import base64 class EncryptedTextField(models.TextField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cipher_suite = Fernet(settings.ENCRYPTION_KEY) def get_prep_value(self, value): cipher_text = self.cipher_suite.encrypt(value.encode('utf-8')) return base64.urlsafe_b64encode(cipher_text).decode('utf-8') def from_db_value(self, value, expression, connection): decrypted_text = self.cipher_suite.decrypt(base64.urlsafe_b64decode(value)) print("hitesh") It just gives me "Invalid token" error while decrypting.it is just giving error in the from_db_value funtion.I have Tried this without django also and it is working fine even with the same key provided above. I don't know how to deal with this error. please help me! -
is adding a table for video, image, and audio a good job for normalizing the database or not
I have an app that has a lot of videos, audios, and images about persons, events, diaries and so on. is it a good practice to having a distinct table for all types of multimedia to query over them and their information and detail fields or there is another good way to handle this mission. evenly, if this is a good solution for normalizing the database, or not? I explored into the net but did not see any complete description about if there is a way to distinct multimedia from tables and just pointing to them through using queries and joining tables, or this is the common way that professional developers do! -
How to fix "Cannot operate on a closed database." while using dumdata in Django
does anybody knows how to fix this problem? sqlite3.ProgrammingError: Cannot operate on a closed database. I just want to finish the command to create a dump of my models. python manage.py dumpdata > .\fixtures\goods\cats.json I dii a little research, it gave me information that this error is connected with wrong encoding in db. Any ideas? I have tried to recreate a db twice, tried to force db work with utf8 encoding using parameters with dumdata -
Docker: django.db.utils.OperationalError: connection to server at "db" (172.19.0.2), port 5432 failed: fe_sendauth: no password supplied
I tried to test the origin code from CS50 Web/Testing/airline1, but I failed to run Docker Container. When I type in terminal: docker-compose up It shows me error message and I cannot open the port http://0.0.0.0:8000/flights/ I have also tried: docker run -e POSTGRES_PASSWORD=password postgres:9.6 And still doesn´t work.. If anybody could help me please? Here are the Error message I got: C:\Users\zhoua\CS50_web\Testing\src7\airline1>docker-compose up [+] Running 2/0 ✔ Container airline1-db-1 Created 0.0s ✔ Container airline1-web-1 Created 0.0s Attaching to db-1, web-1 db-1 | db-1 | PostgreSQL Database directory appears to contain a database; Skipping initialization db-1 | db-1 | 2024-02-02 13:40:04.790 UTC [1] LOG: starting PostgreSQL 16.1 (Debian 16.1-1.pgdg120+1) on x86_64-pc-linux-gnu, compiled by gcc (Debian 12.2.0-14) 12.2.0, 64-bit db-1 | 2024-02-02 13:40:04.794 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db-1 | 2024-02-02 13:40:04.794 UTC [1] LOG: listening on IPv6 address "::", port 5432 db-1 | 2024-02-02 13:40:04.809 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db-1 | 2024-02-02 13:40:04.822 UTC [29] LOG: database system was shut down at 2024-02-02 13:37:09 UTC db-1 | 2024-02-02 13:40:04.835 UTC [1] LOG: database system is ready to accept connections web-1 | Watching for file changes with StatReloader web-1 | System check … -
How to change default Order from ASC to DESC in django OrderFilter
I am not an expert django dev. I was trying to write a viewset which has the ordering_fields and ordering fields, but this ordering field does not have any effect. My viewset is, class ContentViewSet(viewsets.ModelViewSet): queryset = Content.objects.all() serializer_class = ContentSerializer filter_backends = [OrderingFilter] ordering_fields = ['created_at'] ordering = ['-created_at'] What I am looking for is, it will provide the list in descending order. However, if I add a negative sign infront of created_at in the url, it gives me what I am looking for, but I was looking for a solution where I will get the same result without using that negative sign in the url. Thanks in advance. -
How to use DateField in an ArrayField in django
I'm trying to use ArrayField in my model. I get it working with, e.g., IntegerField, but not DateField. So I'm wondering, is there some limitation I'm not aware of, or is there a bit missing in my code that prevents it from working? In my models.py, I added the field with class Directive(models.Model): id = models.AutoField(primary_key=True) ... individual_dates = ArrayField( models.DateField(auto_now_add=False, blank=True, default=date.today), default=list,) test = ArrayField(models.IntegerField(blank=True), default=list,) ... and in my forms.py, I have class DirectiveForm(forms.ModelForm): individual_dates = SimpleArrayField( forms.DateField(), required=False, help_text='comma separated list of dates', widget=DatePickerInput(options={'format': 'DD.MM.YYYY'})) test = SimpleArrayField( forms.IntegerField(), required=False, help_text='comma separated list of ints') ... The form renders fine: Now, when I enter a comma seperated list of integers in the "test" field, the values are stored in the database as expected. when I try to enter a number of dates in the "individual dates" field using the DatePicker, every pick overwrites the previous one, and the last one is eventually stored in the database. when I enter a comma separated list of dates by hand, only the first entry is stored in database. But, when I use the django shell, import my model and try to enter dates there, it works as expected: >>> … -
TypeError at / Field 'id' expected a number but got ... django
Hello to all the programmers, I am a Django Developer, when I run my site without an account, the server got this error: TypeError at / Field 'id' expected a number but got <SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x0000025D3D8E2F90>>. My views.py is: def homepage(request): if request.user.is_authenticated: print("ok") user = request.user posts = Posts.objects.all() sortedk = sorted(posts, key= lambda f: f.lan(), reverse=True) comments = [] pictures = [] com = [] comments_pictures = [] for i in sortedk: lst = [] id = i.id poste = Comments.objects.filter(post_name_id = id) com.append(poste) num = len(poste) prf = Profile.objects.get(id = i.writer_id) pictures.append(prf.avator) comments.append(num) for comment in poste: idh = comment.author_id kk = Profile.objects.get(id = idh) lst.append(kk.avator) comments_pictures.append(lst) print(comments_pictures) if request.method == "POST": form = CommentForms(request.POST) if form.is_valid(): ns = form.save(commit=False) ns.author = user ns.post_name_id = int(request.POST.get("pk")[0]) ns.save() return redirect('home:homepage') else: form = CommentForms() cont = { "user":user, "posts":sortedk, 'comments':comments, "pictures":pictures, "pos":com, "form":form, "comment_pictures":comments_pictures, } return render(request, 'home/home.html',cont) else: return render(request, "home/home.html") Please help me in it. How can I fix it? Is there anyway? -
Problem with context processor in async django
My django app has following features: A model with an async method. An async view. A context processor that call an async method from the model and modifies the response context from the view. I am using Django 5.0 and python 3.12, daphne as asgi server. What's my problem: It appears that as of now django does not differentiate between sync and async context processors. From django source (django/template/context.py): updates = {} for processor in processors: context = processor(self.request) print(f"Context processor {processor.__qualname__}") try: updates.update(context) except TypeError as e: raise TypeError( f"Context processor {processor.__qualname__} didn't return a " "dictionary." ) from e So if a context processor is async, django internals will just try to update response context with a coroutine and cause a Context processor ... didn't return a dictionary. exception. So I tried to make my context processor synchronous by wrapping a call to the async model method with asgiref.sync.async_to_sync. Regardless of setting the force_new_loop parameter I am getting You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly. exception. Am I missing something or is django async support just not at the point where it can provide the … -
Django_rest_framework Page Not Found
When I have been trying 127.0.0.1:8000/api/ it's working but when I've been trying 127.0.0.1:800/api/rota it isn't working. I don't know what is wrong. When linked urls.py files. below the code of the the file:url.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('base.urls')), **path('api/', include('base.api.urls'))**, ] I included the api/urls.py below the code of the file: api/url.py from django.urls import path from . import views urlpatterns = [ path('', views.getMessage), path('rota/', views.getRoutes), ] I linked the url with methods. below the code of the file: api/view.py from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def getRoutes(request): routes=[ 'GET api/' 'GET api/rota' ] return Response(routes) @api_view(['GET']) def getMessage(request): return Response("ok!") Does someone know how to fix it? Here some pictures about the case: [127.0.0.1:8000/api/][1] [127.0.0.1:8000/api/][2] [1]: https://i.stack.imgur.com/c7CoF.png [2]: https://i.stack.imgur.com/b5cok.png I am looking for a solution... -
Gunicorn worker timeout - Which gunicorn worker sync vs gthread
I am using Django and Django Rest Framework (DRF) for my project. In production, when I make HTTP requests, Gunicorn module on the server creates another worker to process that request. This process requires two workers: one to handle the Django request and another that is spawned when the Django code makes an HTTP request to the DRF view. After a while, I frequently find myself experiencing long response times, eventually leading to a 502 Gateway Error. Upon examining the logs, I discovered that all my workers were busy and waiting for the DRF response. Simultaneously, different clients made requests, but there were no available workers to handle these new HTTP requests (I am using 3 workers with Gunicorn's default synchronous worker model). How can I manage this situation when there are multiple simultaneous requests? -
Celery Task with AWS SQS Broker Cancels Immediately After Starting in Docker Environment
I'm experiencing an issue where a Celery task, configured with an AWS SQS broker, starts and then immediately cancels when run in a Docker environment. This behavior occurs despite the task executing successfully when run from PyCharm on the same machine. Below is the relevant part of the Celery configuration and the debug output I receive when the task is executed. Environment: Django version: 4.2 Celery version: 5.3.6 Broker: AWS SQS Deployment: Docker Celery configuration: from __future__ import absolute_import, unicode_literals from celery import Celery, shared_task from firmwave import settings app = Celery( 'firmwave', broker=f'sqs://{settings.AWS_SQS_ACCESS_KEY}:{settings.AWS_SQS_SECRET_KEY}@', ) app.conf.broker_transport_options = { 'region': settings.AWS_SQS_REGION, 'predefined_queues': { 'celery': { 'url': settings.AWS_QSQ_QUEUE_URL, 'access_key_id': settings.AWS_SQS_ACCESS_KEY, 'secret_access_key': settings.AWS_SQS_SECRET_KEY, }, }, 'is_secure': True, } app.conf.enable_utc = True app.conf.broker_connection_retry_on_startup = True app.autodiscover_tasks() Debug output: [DEBUG/MainProcess] Event request-created.sqs.GetQueueAttributes: calling handler... [DEBUG/MainProcess] Response body: b'<?xml version="1.0"?><GetQueueAttributesResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/">**<GetQueueAttributesResult><Attribute><Name>ApproximateNumberOfMessages</Name><Value>155</Value></Attribute></GetQueueAttributesResult>**<ResponseMetadata><RequestId>922533a1-ce80-5018-8f23-6d970e5039f6</RequestId></ResponseMetadata></GetQueueAttributesResponse>' [2024-02-02 10:06:08,319: DEBUG/MainProcess] Event needs-retry.sqs.GetQueueAttributes: calling handler <botocore.retryhandler.RetryHandler object at 0xffffb3475970> [DEBUG/MainProcess] Sending http request... [DEBUG/MainProcess] Certificate path... [DEBUG/MainProcess] Response headers... [DEBUG/MainProcess] Response body... [DEBUG/MainProcess] No retry needed. [DEBUG/MainProcess] Canceling task consumer... [DEBUG/MainProcess] Closing consumer channel... The Celery worker starts and appears to connect to AWS SQS successfully, but then cancels the task consumer and closes the channel without processing any tasks. Ensuring that the … -
Automatically set author on POST
I'm working on a events administration app powered by Django APIRest. When a user post a event is considered the author and I wonder what is the most elegant/professional way to do it: Override the post view Override the create model method Override the save serializer method This is what I currently have (option 1) The models.py: class Events(models.Model): title = models.CharField(max_length=200) description = models.CharField(max_length=200) dateday = models.DateTimeField() start_hour = models.TimeField(null=True) end_hour = models.TimeField(null=True) author = models.ForeignKey(Users, on_delete=models.CASCADE) The serializers.py: #... class EventsSerializer(serializers.ModelSerializer): class Meta: model = Events fields = '__all__' class UsersSerializer(serializers.ModelSerializer): events = EventsSerializer(many=False,read_only=True) class Meta: model = Users fields = '__all__' extra_kwargs = {'password': {'write_only': True}} #... The views.py: #... class EventsList(ListCreateAPIView): queryset = Events.objects.all() serializer_class = EventsSerializer def post(self, request): request.data['author'] = request.user.pk return super().post(request) #... It works, but I still have to prevent changing the author in a PUT request. There's a better way to minimize code or make it reusable? I tried the solution here: class EventsList(ListCreateAPIView): queryset = Events.objects.all() serializer_class = EventsSerializer def perform_create(self, serializer): serializer.save(author=self.request.user) but it does not work: a POST with a body without author the response is that the field author is required. -
Why is my Django signal file not working after setting it up?
I'm trying to send an email to a seller after a buyer completes their payment but I'm facing some issues and the email was not sent. I added a print statement and a try-except block so that I can use that to debug but the print statement did not bring any information in the console and the try block did not return any success or error message in the console too. Please help. Here's my signals.py file # Stdlib Imports import uuid # Django Imports from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from django.core.mail import send_mail from django.conf import settings # Own Imports from payment.models import PaymentHistory @receiver(pre_save, sender=PaymentHistory) def create_ref_code_if_does_not_exist(sender, instance, **kwargs): """ Creates a reference code that will be used by paysack; if one does not exist. """ if not instance.ref_code: instance.ref_code = uuid.uuid4() @receiver(post_save, sender=PaymentHistory) def send_payment_notification_email(sender, instance, created, **kwargs): if created and instance.status == 'completed': print("PaymentNotificationEmail signal triggered.") # For debugging # PaymentHistory model has a ForeignKey to the BuyerOrderHistory model buyer_order = instance.order # BuyerOrderHistory has a ForeignKey to the Product model product = buyer_order.product # Get the seller's email address and name seller_email = product.user.email seller_name = product.user.full_name # Compose the email … -
I can't call the data properly into my html page
I am trying to pull data from the SQL Table that I have and I am able to create a for loop for the number of items i have in the table but i am unable to pull the data. main.py @app.route("/Playback" , methods=['GET', 'POST']) def Playback(): cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor) cursor.execute("SELECT * FROM `movies`") query = cursor.fetchall() return render_template('playback.html', cursor=cursor, query=query) playback.html <table> <tr> <td>Movie Name:</td> <td>View</td> <td>Delete</td> </tr> {% block content %} {% for obj in query %} <tr> <td><p>{{ cursor['movie_name'] }}</p></td> <td><button>View</button></td> <td><button>Delete</button></td> </tr> {% endfor %} {% endblock %} </table> Here is what I have tried and the results are in the picture below results i am trying to pull the movie name from the table movies but the movie names from the table is not appearing. Please help. Thank you in advance. -
When is the django db connection made for the tasks in case async operations or django-q?
I want to know when the db connection is made in case of async operations or django-q. My CONN_MAX_AGE = 0 and in the docs this is written, The default value is 0, preserving the historical behavior of closing the database connection at the end of each request. I want to understand what a request mean in this case? Does it mean web requests only? If yes when is the db connection opened or closed in case of async operations or in case of django_q. -
AttributeError at /users/login/ 'Form' object has no attribute 'email'
I'm creating API for login_view, but I have a problem with a Form. Im using Django-ninja so I created serializers.py and have class LoginInput(Schema): email: str password: str from django.shortcuts import get_object_or_404 from ninja import NinjaAPI, Query, Form from ninja.responses import Response from main.models import Category, City, DeliveryPoint, Product, Cart, CartItem from user.models import User from .serializers import * from typing import List from user.forms import UserLoginForm, UserRegistrationForm from user.utils import generate_jwt_token, decode_jwt_token from ninja.security import HttpBearer from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import get_user_model User = get_user_model() @api.post("/login/") def login_api_view(request, login_data: LoginInput = Form(...)): if request.method == "POST": email = login_data.email password = login_data.password form = UserLoginForm(request, data={"username": email, "password": password}) print(form.errors) if form.is_valid(): user = form.get_user() if user is not None: password = form.cleaned_data["password"] if user.check_password(password): token = generate_jwt_token(user) return {"message": "User Signed In", "token": token} return Response({"message": "Invalid credentials"}, status=400) return Response({"message": "Invalid request method"}, status=405) I'm creating front-end with NextJS. when I go to api/docs I can log in, authenticate and etc, but on actual website I have a problem and cant log in. it says that Form has no attribute 'email'. class UserLoginForm(AuthenticationForm): class Meta: model = User fields = ['email', 'password'] PLEASE HELP ME … -
How do I do a Django authorization data check?
So, I wrote the code for the reg.html page. If the registration data is filled in correctly, the form is saved and the account is created. I checked everything, the data is entered into the database. The only thing left to do is to make authorization. But here's the question - how do you do a check for the correct data? To put it simply, if the user logs in and such an account actually exists, then it should be redirected to the main page. Otherwise, the site will display "There is no such account". Here is the code below. views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from .form import SignUpForm, RegisterForm from .models import Registration def index(request): return render(request, 'main/index.html',) def about(request): return render(request, 'main/about.html') def register(request): if request.method == 'POST': form = RegisterForm(request.POST) if form.is_valid(): form.save(commit=False) return redirect('log') form = RegisterForm() return render(request, 'main/reg.html', { 'form': form }) def log(request): if request.method == "POST": form = SignUpForm(request.POST) if form.is_valid(): if Registration().objects.filter().exists(): return HttpResponse('Да') else: return HttpResponse('Нет') form = SignUpForm() return render(request, 'main/log.html', { 'form': form }) -
LDAPBackend authenticate return INVALID_CREDENTIALS
I have an issue when I do in login_form.py : from django_auth_ldap.backend import LDAPBackend auth = LDAPBackend() user = auth.authenticate(request, username=User_Name, password=User_Password) this does return Caught LDAPError while authenticating User_Name: INVALID_CREDENTIALS({'msgtype': 97, 'msgid': 1, 'result': 49, 'desc': 'Invalid credentials', 'ctrls': [], 'info': '80090308: LdapErr: DSID-0C090569, comment: AcceptSecurityContext error, data 52e, v4563'}) but when I do in login_form.py : import ldap con = ldap.initialize('LDAP://URL ') con.simple_bind_s('User_Name', 'User_Password') This does work as excepted. In my setting.py I have set the LDAP as follow : AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] LDAP_IGNORE_CERT_ERRORS = True AUTH_LDAP_START_TLS = False AUTH_LDAP_SERVER_URI = "LDAP://URL" # Use the NTLM format for domain authentication AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 # You can add other options if needed } AUTH_LDAP_BIND_DN = "CN=BIND_USER,OU=AZE Users,DC=aze,DC=azerty,DC=priv" AUTH_LDAP_BIND_PASSWORD = "BIND_PASSWORD" AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=AZE Users,DC=aze,DC=azerty,DC=priv",ldap.SCOPE_SUBTREE,"(sAMAccountName=%(user)s)",) What am I doing wrong ? -
Prevent a logged in user from peeping into other client's orders
class OrderDetailView(LoginRequiredMixin, DetailView): model = Order def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["object_list"] = self.object.selectedproduct_set.all() if context["object_list"].first(): if context["object_list"].first() != self.request.user: return {} context["grand_total"] = get_total(context["object_list"]) return context This is for an online shop. LoginRequiredMixin checks only whether a user is logged in or not. But a logged in user can view somebody else's orders. That is a busybody user can iterate through orders manually like /orders/15, /orders/16 and have a look at the contents. It is intolerable. To the best of my ability I prevented that by checking if the user is the owner of the order. But this is clumsy: we should send 403 status or something rather than just showing an empty list. Could you help me understand how to do that? -
Trouble with a contact form, sending emails using Gmail, was working great now I've added new html files to another app it's stopped working
I had my emails generating in the terminal in development and to my Gmail in production. All working very well. Once I done a bit more code which involved static sites and a modal on another app in my django project. It now doesn't work. If I roll back my project it works again. So it's something I've done, however, I haven't changed anything on my contact app. Can anyone suggest anything please https://github.com/StaceyRb89/transcribe.git I removed the custom javascript, and bootstrap javascript from the base.html hoping it could have been that, but it didn't make a difference, so the home page burger button doesn't work as well as it should. But it was to try it out. I have messed around with settings. I even copied the older commit directly to it which was exactly the same bar the two src js files, I don't know what else to do. I have searched and should probably mention I've only been coding for 5 months. Thank you -
Django SimpleUploadedFile is not being sent
I'm developing Django application and wrote a test that checks if view method acts correctly. I need to send some data in request, including the image file. In my case: def setUp(self): ... self.image_file = SimpleUploadedFile("test_image.jpg", b"file_content", content_type='image/jpeg') ... def test_save_image_instance(self): ... files = {'image': self.image_file} response = self.client.post(endpoint, data=data, files=files) # assertions there ... I double-checked, everything is correct, there is SimpleUploadedFile instance in file dictionary. But in the view request.FILES is empty (<MultiValueDict: {}>), though data was sent correctly. Also, if I look into request.META there is 'files': {'image': <SimpleUploadedFile: test_image.jpg (image/jpeg)>}, which indicates that the file should be there. Django CommonMiddleware is set correctly, type of content in the request is multipart/form-data I tried using UploadFile class instead of SimpleUploadFile, checking values in different places of the program to find the problem, but it didn't help. -
I am working on generating mail for new users. writing html code with inline css in Django. Here I have to check outlook,web,mobile&chrome screens
Here is my sample code '\ ' '\ ' Your username is : '+ toaddr +''\ ' You can set your password using below button: '\ ' '\ ' '\ ' Set Your Password →'\ ' '\ ' '\ ' '\ ' '\ But, in outlook border-radius is not working & in google mail it is not getting properly. How I can make proper for outlook & mail & mobile versions? I tried many things for border radius and View for google mail but nothing works. -
When using two databases in tests, django applies migrations to both
I have two databases: "default" and "logs". "logs" is MongoDB which is used for logging. Here are my settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'project', 'HOST': 'localhost', 'PORT': 5432, 'PASSWORD': 'passwd', 'USER': 'user', }, "logs": { "NAME": "djongo", "ENGINE": "djongo", 'HOST': 'localhost', 'PORT': 27017, "USER": "user", "PASSWORD": "passwd", }, } I also wrote a router class LogsRouter: route_app_labels = {"logging_system"} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return "logs" return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.route_app_labels: return "logs" return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth and contenttypes apps only appear in the 'auth_db' database. """ if app_label in self.route_app_labels: return db == "logs" return None In the test I added two databases: class TestTestCase(TransactionTestCase): databases = ["default", "logs"] When starting I get the error: djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: …