Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using Google Cloud SDK in Django Developement and UWSGI
I am trying to access Google Cloud Service in my backend process (views.py). I have successfully run this in developement server. Here is my views.py script : from google.cloud import bigquery @login_required def update_iphone(request): user_profile = UserProfile.objects.get(user=request.user) client = bigquery.Client() if request.method == 'POST': form = IphoneUpdateForm(request.POST) if form.is_valid(): sql = f""" query script """ client.query(sql) else: pass sql = f""" query script """ corporate_list = client.query(sql).to_dataframe() iphone_form = IphoneUpdateForm() return render(request, 'myapp/home.html', {'user_name':user_profile.first_name, 'corporate_list': corporate_list['corporate_name'].to_list(), 'form': iphone_form}) This views.py script runs well in development server. But if try to run it with UWSGI, I am getting error related to the google cloud as following : google.auth.exceptions.DefaultCredentialsError: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information. My question is why am I getting this error if using UWSGI and not the development server ? how do I deal with this error ? Thank You -
Many one-to-one relationships pointing to the same model Django
I'm designing an application in Django where I have an Item model with numerous attributes for each item. I'm experiencing very poor performance in my application and I'm wondering if there are flaws in my setup that could be causing this issue. I am relatively new to Django, so any pointers would be greatly appreciated. Currently, I have around 200 attribute models, each with optional one-to-one fields linked to an item via a foreign key as follows: Attribute models: class AttrBase(models.Model): prev_value = models.CharField(max_length=250, null=True, blank=True) edited_by = models.ForeignKey( Account, on_delete=models.CASCADE, null=True, blank=True ) edited_on = models.DateTimeField(null=True, blank=True) options = None class Meta: abstract = True class ID(AttrBase): item = models.OneToOneField(Item, on_delete=models.CASCADE) value = models.CharField(max_length=250, null=True, blank=True) name = "ID" tooltip = "..." group = "..." class Height(AttrBase): item = models.OneToOneField(Item, on_delete=models.CASCADE) value = models.IntegerField(null=True, blank=True) name = "Height" tooltip = "..." group = "..." ...more I am also using a generic relationship to link to all of the groups, as follows: class AttributeGroup(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to={"app_label": "attributes"}, ) name = models.CharField(max_length=250, null=True, blank=True) description = models.CharField( max_length=1000, default="TODO", null=True, blank=True ) def __str__(self): return str(self.content_type) def save(self, *args, **kwargs): self.name = self.content_type.name super(AttributeGroup, self).save(*args, **kwargs) This … -
Django CSRF cookie not set with 403 error for webhook URL
I am encountering an issue with Django's CSRF protection while trying to handle Stripe webhooks on my local host. I am receiving a 403 Forbidden error with the message "CSRF cookie not set." The error occurs when trying to access the /collect-stripe-webhook/ URL, which is intended to handle incoming webhook requests from Stripe.Also the payments go through and payment is successfull urls.py urlpatterns = [ path('subscribe/', product_list, name='product_list'), path('create-checkout-session/<int:product_id>/', create_checkout_session, name='create_checkout_session'), path('collect-stripe-webhook/', stripe_webhook, name='stripe_webhook'), # Updated path path('success/', TemplateView.as_view(template_name="subscriptions/success.html"), name='success'), path('cancel/', TemplateView.as_view(template_name="subscriptions/cancel.html"), name='cancel'), ] views.py: @csrf_exempt def stripe_webhook(request): """ View to handle Stripe webhooks. """ payload = request.body sig_header = request.META.get('HTTP_STRIPE_SIGNATURE', None) endpoint_secret = settings.STRIPE_WEBHOOK_SECRET if not sig_header: logger.error("No signature header found in the request") return JsonResponse({'status': 'invalid request'}, status=400) try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: logger.error(f"Invalid payload: {e}") return JsonResponse({'status': 'invalid payload'}, status=400) except stripe.error.SignatureVerificationError as e: logger.error(f"Invalid signature: {e}") return JsonResponse({'status': 'invalid signature'}, status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] handle_checkout_session(session) return HttpResponse(status=200) template: <form action="{% url 'subscriptions:create_checkout_session' product.id %}" method="POST"> {% csrf_token %} <button type="submit">Subscribe</button> </form> Error Message: Forbidden (CSRF cookie not set.): /collect-stripe-webhook/ Question: What could be causing this issue with Django's CSRF protection, and how can I resolve … -
How are connections handled by SQLAlchemy internally
Context Hello, I mostly use Django for my main backend monolith. In Django, you do not need to handle db connections on your own, this is abstracted (because Django uses the Active Record pattern instead of the Data mapper pattern used by Sqlalchemy). I have been doing some reading and I feel like I know the basics of the different constructs of Sqlalchemy (like engine, connection, and session). Nonetheless, we have started to scale our FastAPI + Sqlalchemy apps, but I have found this error appearing: sqlalchemy.exc.TimeoutError - anyio/streams/memory.py:92 - QueuePool limit of size 8 overflow 4 reached, connection timed out, timeout 10.00 I would like to understand why that is happening. Current setup Right now we have instances of the web server running, using the following command: python -m uvicorn somemodule.api.fast_api.main:app --host 0.0.0.0 As you can see, I'm not setting the workers flag, so uvicorn is only using 1 worker. On the SQLAlchemy engine, we are using the following options: SQLALCHEMY_ENGINE_OPTIONS = { "pool_pre_ping": True, "pool_size": 16, "max_overflow": 4, "pool_timeout": 10, "pool_recycle": 300, } engine = create_engine(get_db_url(), **SQLALCHEMY_ENGINE_OPTIONS) Questions Q1: does this apply to every worker of uvicorn? My guess is that if I spin two workers in uvicorn, … -
Using Django and reportlab to create a pdf. Report is failing when I try to include a field that is tied to a foreign key
My attempt at making a pdf fails with a server500 error when I attempt to export a field that is created by a foreign key. I believe this to somehow be the problem, as all other fields work as expected. This same field can be similarly exported as a csv. in views.py: def report_pdf(request): # Create a Bytestream buffer buf = io.BytesIO() # Create a canvas c = canvas.Canvas(buf, pagesize=letter, bottomup=0) # Create a text object textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) # Designate the model customers = Customer.objects.all() lines =[] for customer in customers: lines.append(customer.address) lines.append(customer.address2) lines.append(customer.city) lines.append(customer.province3) # Loop for line in lines: textob.textLine(line) # Finsih up c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='customer_list.pdf') and in models.py class Customer(models.Model): address = models.CharField(max_length=100, null=True, blank=True) address2 = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) province3 = models.ForeignKey(Province, null=True, blank=True, on_delete=models.PROTECT) and the foreign model: class Province(models.Model): province = models.CharField(max_length=2) def __str__(self): return(f"{self.province}") I've tried disabling the province3 field, at which point it works. Am I correct that it has to do with the fact that it uses a foreign key? If so, what may be the problem? I have checked the site logs and the apache … -
why my django resgistration view not able to add new users?
I have below DRF APIView, I am building a basic user registration with OTP class RegisterView(APIView): permission_classes = [AllowAny] def get(self, request, *args, **kwargs): return render(request, 'registration.html') def post(self, request, *args, **kwargs): serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() # Send verification email with OTP otp = generate_otp() user.otp = otp user.otp_expiry = datetime.now() + timedelta(minutes=5) user.save() send_verification_email(user.email, otp) return Response( { 'message': 'Account created successfully. Please verify your email.', "status": status.HTTP_201_CREATED, } ) return Response( { 'message': serializer.errors, "status": status.HTTP_400_BAD_REQUEST, } ) The above function is calling below two functions def generate_otp(): return str(random.randint(100000, 999999)) def send_verification_email(email, otp): subject = "Verify Your Email Address" template_name = "email_verification.html" context = {"otp": otp} html_content = render_to_string(template_name, context) text_content = strip_tags(html_content) msg = EmailMessage(subject, text_content, to=[email]) msg.content_subtype = "html" msg.send() The register.html as below <form id="register-form"> {% csrf_token %} <div class="form-group"> <label for="email">Email Address:</label> <input type="email" class="form-control" id="email" name="email" required> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" id="password" name="password" required> </div> <button type="submit">Register</button> </form> <script> document.getElementById('register-form').addEventListener('submit', function(event) { event.preventDefault(); const formData = new FormData(event.target); const jsonData = {}; for (const [key, value] of formData.entries()) { jsonData[key] = value; } fetch('{% url "register" %}', { method: 'POST', headers: { 'Content-Type': 'application/json' … -
how to resolve the following issue while downloading cs_oracle library for django project
enter image description here I want to connect oracle db to my django project. I tried to install 'cx_oracle' library but it is throwing the attached error. How can I resolve this issue? Is there any other way of connecting oracle db to django project? -
django-simple-captcha Not Displaying Image in Production
I'm encountering a problem with Django-Simple-Captcha in my Django project's production mode (server). The CAPTCHA image is not displaying, while it works correctly in development (local environment). django==3.2.9 django-simple-captcha==0.5.17 -
What is the correct way to query a many to many relationship in Django efficiently?
I probably haven't phrased this question correctly so apologies. Also probably why I cannot find much information when I google it. Anyway I have a Django project that I am using to create an API using Django Rest Framework. For this problem I have 2 models that are relevant. A Product model and an Offer model (slightly pseudocode so ignore any missing fields). class Offer(models.Model): image = models.ImageField(upload_to=upload_to, validators=(validate_image_file_extension,)) discount = models.IntegerField(validators=(MinValueValidator(0), MaxValueValidator(100))) start_date = models.DateField() expiration_date = models.DateField() products = models.ManyToManyField(Product, related_name='offers') customers = models.ManyToManyField(Customer) So as you can see in this model. There's a many to many link to the Product model. Inside the product model is just some standard stuff: class Product(models.Model): name = models.CharField(max_length=256) price = models.FloatField() stock = models.IntegerField() product_photo = models.ImageField(null=True, upload_to=product_photo_path, validators=[validate_image_file_extension]) Okay so now for the actual question. I am trying to add a new feature where it gets the discounted price for a product. If there is multiple offers, it needs to return the highest discount price. It also needs to take into account the customer who sends the request because the offers are not relevant for every customer. This needs to be done on the list endpoint from the API … -
How can I disable Chrome pop-ups like this while running automated Selenium tests in Python?
I am currently writing an automated testing suite for a large Django project for my corporation. Everything was going well until I updated Chrome (v.125.0.6422.142) and the Chromedriver (v.125.0.6422.141). When I ran the tests with the head, I saw that there was a Chrome Tip that popped up from the vertical ellipsis that opens the Chrome menu: Stupid message messing up my tests I checked with a custom GPT (using GPT-4) to see if this was causing potential issues, and had it confirmed (for what it's worth) that this popup indeed would be causing interference in my tests. However, I am unsure of how to get rid of it. I went through Stack OverFlow, GPT, and Github Copilot, and I implemented the following arguments to my setup: def setUpClass(cls): super().setUpClass() if os.environ.get('ENVIRONMENT') == 'LOCAL': # Retrieve the path from an environment variable chromedriver_path = os.environ.get('CHROMEDRIVER_PATH') if not chromedriver_path: raise ValueError("The CHROMEDRIVER_PATH environment variable must be set.") chrome_service = Service(executable_path=chromedriver_path) # Option to run in headless mode if os.environ.get('HEADLESS') == 'True': print("Running in headless mode.") chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--enable-logging') cls.selenium = webdriver.Chrome(service=chrome_service, options=chrome_options) else: chrome_options = Options() chrome_options.add_argument('--disable-first-run-ui') chrome_options.add_argument('--no-first-run') chrome_options.add_argument('--disable-extensions') chrome_options.add_argument('--enable-logging') chrome_options.add_argument('--disable-popup-blocking') chrome_options.add_argument('--disable-notifications') chrome_options.add_argument('--disable-infobars') chrome_options.add_argument('--disable-blink-features=AutomationControlled') cls.selenium = webdriver.Chrome(service=chrome_service, options=chrome_options) cls.selenium.maximize_window() … -
django user login gives error always as the admin with this phone number already exist
I have a custom user model with username field phone_number inherited from AbstractBaseUser and PermissionMixin.I have multiple collge and each college has separate custom admin panel.I have created a admin for each college and i have create a login template to login each college admin. view.py def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): phone_number = form.cleaned_data['phone_number'] password = form.cleaned_data['password'] user = authenticate(request, username=phone_number, password=password) print(f"phone_number: {phone_number}") print(f"password: {password}") print(f"User: {user}") if user is not None: auth_login(request, user) messages.success(request, "Login successful") return redirect('dashboard') else: messages.error(request, "Login failed. Enter valid credentials and try again.") else: messages.error(request, "Form is invalid. Please check the entered data.") else: form = LoginForm() return render(request, 'accounts/login.html', {'form': form}) models.py class Custom_user(AbstractBaseUser,PermissionsMixin): phone_number=models.CharField(max_length=13,validators=[phone_validator],unique=True) USERNAME_FIELD='phone_number' REQUIRED_FIELDS=[] is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) objects = Custom_user_manager() def __str__(self) -> str: return self.phone_number class Meta: verbose_name = 'Admin' verbose_name_plural = 'Admins' form.py class LoginForm(forms.ModelForm): class Meta: model = Custom_user fields = ['phone_number', 'password'] widgets={ 'password':forms.PasswordInput(), } def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.fields['phone_number'].widget.attrs.update({'class': 'form-control'}) self.fields['password'].widget.attrs.update({'class': 'form-control'}) Whenever i click the login button it gives the error as The admin with phone number already exist -
change selinux policy to allow gunicorn access
How do I create a selinux policy to allow gunicorn to operate with nginx for a django managed web site? I know there's a way to do it, but don't understand selinux' arcane policy definitions --YES, I have read the documents. If I disable selinux with "setenforce 0", then "systemctl start gunicorn" loads gunicorn. If selinux is set to enforcing (setenforce 1), the systemctl command fails. This is definitely a policy issue. So, can anyone describe how to set the policy to allow gunicorn to load? Thanks, Joe White -
Why 'coverage' considers all of my class-based-views as tested?
I'm just learning django testing. When I use 'Coverage' module to check which parts of my code is tested, it considers almost all of class-based-views as tested while I have commented out all of my tests. I investigated this problem and found that in urls.py I have this line: from . import views It seems importing views.py file or just a class from views.py make all classes in views.py run once e.g. the print line in this code will be executed: class AuthorDelete(PermissionRequiredMixin, DeleteView): model = Author success_url = reverse_lazy('authors') permission_required = 'catalog.delete_author' print("----- AuthorDelete -------") And 'Coverage' will mark them as tested. But obviously this class is not tested at all. How can I get real and exact test coverage report? Should I use other tools rather than 'Coverage'? Thanks in advance -
Django blog website rejected in AdSense approval
I applied my www.admoha.com website for adsense but it rejected with policy error so please check my site : www.admoha.com and give me suggestions to fix it. I want to approved my website: www.admoha.com in Google adsense. -
Tips for Django Optimization
i'm looking for tips on things to check next in order to increase the efficiency of my django in production. The loading times vary wildly; sometimes the page are loaded in 200ms, sometimes they require multiple seconds. I've worked extensively on SQL and cache; see the attached image, they take a combined 25ms. Yet the page required almost 10 seconds to load. As techical information, I'm using postgresql (CONN_AGE set to 6), nginx (12 workers on 6 processors), and django-redis-cache. What can I look for next? I've tried to work extensively on SQL and cache, in order to see a consistent reduction on loading times, yet in some occasions the page require multiple seconds to load. -
Java Script for insert html does not work
I load posts when scrolling the page, and for some reason the script for opening a photo of a post or liking a post does not work, I thought for a long time why this was, but I still don’t understand. views.py For the start page (posts that are loaded immediately, and not by scrolling the page), everything is ok. posts.html And if it helps, here's a piece of the script that doesn't work (all of it doesn't work): posts_script.js I checked a lot of things, it seems like all the classes are needed, the data of tags are also normal, that is, everything is there for the script to work, but for some reason it doesn’t want to work, I would be very grateful if you help me. -
How to create a generic relationship without adding dependency between apps in Django?
I have an ecommerce store app that have those apps: core: specific for the ecommerce store app needs. likes: independent reusable app that is supposed to be used with different models from other apps. store: independent reusable app that has the models and views for the ecommerce app. Now I want to add the ability for the user to like a product, so I want to add a like (from likes) to the product (from store), how can I do it without adding explicit dependency (import likes in store) between the two apps? The LikedItem model from likes app: from django.conf import settings from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey class LikedItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() The Product model from the store app: class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) unit_price = models.DecimalField( max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField(validators=[MinValueValidator(0)]) last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey( Collection, on_delete=models.PROTECT, related_name='products') promotions = models.ManyToManyField(Promotion, blank=True) def __str__(self) -> str: return self.title class Meta: ordering = ['title'] I tried implementing this in the core app, I started with creating a CustomProduct model that extends … -
Unexpected Loss of User Authenticated State Between Two Seperate Django Views
I'm having an issue with user authentication using the social-auth-app-django library in my Django project. After the user is successfully authenticated via a social provider (in this case, Google), the user doesn't seem to be authenticated when redirected to the dashboard view. Code # Decorator to check if the user is authenticated and verified def verified_user_required(view_func): print('\nDecorator: verified_user_required') @wraps(view_func) def wrapper(request, *args, kwargs): print('Verified user required') if not request.user.is_authenticated: print('User not authenticated') return redirect('login') nwd_user = get_nwd_user(request.user) if not nwd_user or not nwd_user.is_verified(): print('User not verified') return redirect('verify-email') print('User verified') return view_func(request, *args, kwargs) return wrapper # View function to handle social auth callback @psa('social:complete') def auth_callback(request, backend): print("\nView Auth Callback") # Retrieve the backend and user ID from the session backend_name = request.session.get('auth_backend') user_id = request.session.get('authenticated_user_id') print("Backend from session:", backend_name) print("User ID from session:", user_id) # Ensure the backend is correctly set if not backend_name or not user_id: return redirect('login') # Get the user object try: user = User.objects.get(id=user_id) except User.DoesNotExist: return redirect('login') # Log in the user login(request, user, backend=backend_name) # Debugging: Print the backend and user information print("Backend:", backend) print("Request Backend:", request.backend) print("User:", request.user) # Check if the user is authenticated if request.user.is_authenticated: # Perform any additional … -
Django update_or_create efficiency
Is using Model.objects.update_or_create(field1=x, field2=y, defaults=defaults) slower as compared to doing this: qs = Model.objects.filter(field1=x, field2=y) if qs: qs.update(defaults=defautls) else: defaults.update({'field1': x, 'field2': y}) Model.objects.create(**params) -
Yet another BS error from the lovely Django: django.db.utils.IntegrityError: NOT NULL constraint failed
Right, just because I just simply love having my time wasted by Django's silly temper tantrums (because it clearly identifies as a spoiled little five-year-old child and not a framework that just does what the programmer tells it to do), is there any particular valid reason as to why, once again, Django is throwing an "exception" (it's adorable you call it an "exception", i feel "tempter tantrum" would be more of an apt name - I may put that to the Django team as an idea for their next release) of: django.db.utils.TEMPERTANTRUM: NOT NULL constraint failed When this is my model #model.py from django.db import models import uuid # Create your models here. class ServiceDegradations(models.Model): issue_reference = models.UUIDField(primary_key=True, default=uuid.uuid1, editable=False) issue_title = models.CharField(max_length=50) issue_description = models.TextField() issue_date = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Service Degradation's" def __str__(self): return self.issue_title Isn't my life just fantastic, surrounded on a daily basis by stupidity and pointlessness. Well let's see, I added NULL=TRUE, I removed NULL=FALSE, but of course, Django identifying as a spoiled little five year old child, there's not being rational with this framework. -
using runserver in django runs all scripts but using daphne for production runs only asgi.py
I have a problem when i setup django for production for some reason, when i use runserver it checks all the scripts and runs them all completely fine but when i run it using daphne it ignores everything and starts the server immediately here's the structure of my project . ├── Dockerfile ├── chat │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── graph.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_alter_langchainhistorysession_id_and_more.py │ │ ├── 0003_rename_collection_id_langchainembedding_collection.py │ │ ├── 0004_alter_langchainembedding_id.py │ │ ├── 0005_alter_langchainhistorysession_account_id.py │ │ ├── 0006_alter_langchainhistorysession_chat_history.py │ │ ├── 0007_langchainhistorysession_enabled.py │ │ ├── __init__.py │ ├── models.py │ ├── permissions.py │ ├── serializers.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── chatbot │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ ├── asgi.py │ └── wsgi.py ├── data_worker │ ├── __init__.py │ └── utils.py ├── db_init.py ├── docker-compose.yml ├── graph.png ├── gunicorn_conf.py ├── manage.py ├── market_data.json ├── markets.csv ├── nginx │ └── nginx.conf ├── prompt.txt ├── requirements.txt └── wait-for-it.sh asgi.py """ ASGI config for chatbot project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ """ import os from django.core.asgi … -
ModuleNotFoundError error when trying to run Celery workers with versioned Django Rest Framework
I'm seeing the following error when I run my Celery docker container with the following command $ celery -A zen_api.zen_api worker --loglevel INFO celery | Traceback (most recent call last): celery | File "/venv/bin/celery", line 8, in <module> celery | sys.exit(main()) celery | ^^^^^^ celery | File "/venv/lib/python3.12/site-packages/celery/__main__.py", line 15, in main celery | sys.exit(_main()) celery | ^^^^^^^ celery | File "/venv/lib/python3.12/site-packages/celery/bin/celery.py", line 236, in main celery | return celery(auto_envvar_prefix="CELERY") celery | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ celery | File "/venv/lib/python3.12/site-packages/click/core.py", line 1157, in __call__ celery | return self.main(*args, **kwargs) celery | ^^^^^^^^^^^^^^^^^^^^^^^^^^ celery | File "/venv/lib/python3.12/site-packages/click/core.py", line 1078, in main celery | rv = self.invoke(ctx) celery | ^^^^^^^^^^^^^^^^ celery | File "/venv/lib/python3.12/site-packages/click/core.py", line 1688, in invoke celery | return _process_result(sub_ctx.command.invoke(sub_ctx)) celery | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ celery | File "/venv/lib/python3.12/site-packages/click/core.py", line 1434, in invoke celery | return ctx.invoke(self.callback, **ctx.params) celery | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ celery | File "/venv/lib/python3.12/site-packages/click/core.py", line 783, in invoke celery | return __callback(*args, **kwargs) celery | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ celery | File "/venv/lib/python3.12/site-packages/click/decorators.py", line 33, in new_func celery | return f(get_current_context(), *args, **kwargs) celery | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ celery | File "/venv/lib/python3.12/site-packages/celery/bin/base.py", line 135, in caller celery | return f(ctx, *args, **kwargs) celery | ^^^^^^^^^^^^^^^^^^^^^^^ celery | File "/venv/lib/python3.12/site-packages/celery/bin/worker.py", line 348, in worker celery | worker = app.Worker( celery … -
python webapp using django and mongodb
i am doing a web app for a printing shop using django ango mongodb.when i am migrating it shows errors.and changed migraionfile it shows an error like this:Traceback (most recent call last): File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\double_two_Print\manage.py", line 22, in main() File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\double_two_Print\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\core\management_init_.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\core\management_init_.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\core\management\commands\makemigrations.py", line 196, in handle loader.project_state(), ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\db\migrations\loader.py", line 361, in project_state return self.graph.make_state( ^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\db\migrations\graph.py", line 329, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\db\migrations\migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\db\migrations\operations\fields.py", line 93, in state_forwards state.add_field( File "C:\Users\shamz\OneDrive\Desktop\shobi\double2_Project\shoaiba\Lib\site-packages\django\db\migrations\state.py", line 248, in add_field self.models[model_key].fields[name] = field ~~~~~~~~~~~^^^^^^^^^^^ KeyError: ('products', 'product') what it means? i tried to migrate my file.it shows django's problem. -
Django show sqlite data on html site
I'm about to write code for a new web program with Django. So the problem is that I want to have the data from the database (db.sqlite3) on the HTML page and that works fine but only if I add an item, otherwise the data is not shown. I would be really glad if someone can help me. Thanks! Here is my Inventar.html: <!DOCTYPE html> {%load static%} <link rel="stylesheet" href={% static "style.css"%} "type/css"> <html> <head> <style> ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #333; position: fixed; top: 0; width: 100%; } li { float: left; } li a { display: block; color: white; text-align: center; padding: 14px 16px; text-decoration: none; } li a:hover:not(.active) { background-color: #111; } .active { background-color: #04AA6D; } table, th, td { border:1px solid black; } </style> <ul> <li><a class="active" href="/index">Home</a></li> <li><a href="/admin">Admin</a></li> <li><a href="#contact">Contact</a></li> <li><a href="#about">About</a></li> </ul> <br> <br> <h1 style="color:rgb (85, 85, 85);text-align:center;"> Inventar </h1> <a class="Button1" onclick="addItem()">Gegenstand hinzufügen</a> <table> <tr> <th>Name</th> <th>Geräte ID</th> <th>Seriennummer</th> <th>Standort</th> <th>Genauer Standort</th> <th>Lieferant</th> <th>Bemerkungen</th> <th>MAC-LAN</th> <th>MAC-WLAN</th> <th>Status</th> <th>Beschädigung</th> <th>Zubehör</th> <th>Anschaffungsdatum</th> </tr> {% for item in items %} <tr> <td>{{ item.name }}</td> <td>{{ item.geräte_id }}</td> <td>{{ item.seriennummer }}</td> <td>{{ item.standort }}</td> <td>{{ item.genauer_standort }}</td> <td>{{ … -
Prevent django from writing e-mail information to stdout
I'm using django 2.2. with python 3.6. In some cases my server stores stdout into a log used by managers. For some reason django started to write to stdout at send-mail some time ago. The managers do not like it because it looks like en error case for them. So the following sends the e-mail, but also writes to stdout: ^C(venv) > python manage.py shell Python 3.6.15 (default, Sep 15 2021, 12:00:00) Type 'copyright', 'credits' or 'license' for more information IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: from django.core.mail import send_mail In [2]: send_mail( ...: 'Problems in sync script', ...: "kukkuu", ...: 'pxpro_sync@<myOrg>', ...: ['<myEmail>'], ...: fail_silently = False,) connection: {'fail_silently': False, 'host': 'localhost', 'port': 25, 'username': '', 'password': '', 'use_tls': False, 'use_ssl': False, 'timeout': None, 'ssl_keyfile': None, 'ssl_certfile': None, 'connection': None, '_lock': <unlocked _thread.RLock object owner=0 count=0 at 0x7fa8e5a01180>} mail: <django.core.mail.message.EmailMultiAlternatives object at 0x7fa8e59b4ba8> <class 'django.core.mail.message.EmailMultiAlternatives'> Out[2]: 1 How can I get just e-mails sent without anything (like "connection:...") displayed into stdout ?