Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to dumps Python object to JSON without "" using json.dumps()?
I need to request post a 36-digit id with other things to a url. This code should be sent as json. But when I try to json.dumps() it, the initial and final quotes are also counted and as you can see I reach 38 characters and get error. merchant_id='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' merchand_id_json = json.dumps(merchant_id) #check len of merchat id and merchant id in json format print('len merchant_id is', len(merchant_id)) print('len merchand_id_json is', len(merchand_id_json)) # Set header request_header = { 'accept': 'application/json', 'content_type': 'application/json', } # Send request res = requests.post( url=request_url, data= { "merchant_id": merchand_id_json, }, headers=request_header) # Check res content in terminal print('res =', res) # Check res.text in terminal print('res.text =', res.text) in Terminal: len merchant_id befor json is 36 len merchand_id after json is 38 res = <Response [200]> res.text = {"data":[],"errors":{"code":-9,"message":"The input params invalid, validation error.","validations":[{"merchant_id":"The merchant id may not be greater than 36 characters."},{"merchant_id":"string is not a valid uuid."}]}} How can I convert this 36-digit id to json format without increasing the number of characters? -
Why am I getting MultiValueDictKeyError when using requst.files in Django?
I am trying to upload a file to my Django Server using HTML input type file. HTML Code <form action="csv/upload" enctype="multipart/form-data" method="POST"> {% csrf_token %} <input type="file" name="csvFile" accept=".csv"> <button type="submit">submit</button> </form> views.py def upstud(request): var = "0sdfs" my_uploaded_file = request.FILES["csvFile"] num = type(my_uploaded_file) return render(request, "signup.html", {"var": num}) On Submitting the file I get MultiValueDictKeyError at:- my_uploaded_file = request.FILES["csvFile"] I have tried using my_uploaded_file = request.FILES.get("csvFile"]) This simply returns none What is the issue? -
Staff user is getting by default all permission in Django Admin Site - Custom User Model (AbstractBaseUser)
I am using Django custom user model inheriting from AbstractBaseUser & PermissionsMixin. When I make a staff user, the user gets all the permission by default, means staff has superuser privileges of 'view', 'change', 'add', & 'delete' on all the apps and models in django admin site, But when I use Django's built-in User model it works perfectly fine, when a staff user login it says 'you don't have permission' and when I assign the permission I want to give the staff has the only permission in django admin site. my model has both methods with True has_perm() has_module_perms() Do I need to update something which is commonly made mistake? I tried changing has_perm and has_module_perms to return False but it restrict superuser also. -
How to locate django logs in nginx docker setup?
I have my website build using below technology stack, Django GraphQL Postgres Nginx Docker Below is how my docker-compose file looked like, version: "3.9" services: web: extra_hosts: - "host.docker.internal:host-gateway" build: context: . dockerfile: Dockerfile.prod command: gunicorn sports_league.wsgi:application --bind 0.0.0.0:8000 volumes: - .:/code - static_volume:/code/staticfiles - media_volume:/code/mediafiles environment: - PRODUCTION=true env_file: - ./config/.env.prod expose: - 8000 nginx: build: ./nginx ports: - "80:80" depends_on: - web volumes: - static_volume:/code/staticfiles - media_volume:/code/mediafiles volumes: pgdata: static_volume: media_volume: When I run the django app locally, I can see the logs (print statements) on terminal. However when I run it using Docker as a service, I don't see those in the container logs. It looks like nginx is causing this to happen. I check nginx container logs as well, but I cannot find the logs there as well. Below is how my nginx configuration file looks like, upstream sports_league { server web:8000; } server { listen 80; location / { proxy_pass http://sports_league; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; client_max_body_size 100M; } location /static/ { alias /code/staticfiles/; } location /media/ { alias /code/mediafiles/; } } Please help me to locate the logs or those print statements. -
TypeError at /cart/add_cart/7/ _cart_id() takes 0 positional arguments but 1 was given
from urllib import request from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Cart, CartItem from store.models import Product Create your views here. def _cart_id(): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) #get the cart using the cart_id present in the session except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 #cart_item.quantity = cart_item.quantity + 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return HttpResponse(cart_item.product) exit() return redirect('cart') def cart(request,): return render(request, 'store/cart.html') Hey, so basically when I'm running the server to test the "Add to cart" button I get this error. enter image description here -
Django missing underscore in models name from admin
I'm working on a project using Django cookie cutter I have an issue with adding a through model (EventCompetitor) to my app for additional info related to a many to many relationship (competitors). I can see in the db that the through table is called: "events_event_competitor" but Django throws an error in the admin because its trying to query: "events_eventcompetitor". django.db.utils.ProgrammingError: relation "events_eventcompetitor" does not exist what would cause this issue? models.py class EventCompetitor(models.Model): event = models.ForeignKey('Event', on_delete=models.CASCADE) competitor = models.ForeignKey(Competitor, on_delete=models.CASCADE) order = models.IntegerField(default=0) class Meta: unique_together = ('event', 'competitor') class Event(models.Model): """ Default custom evens model for oddsx. """ # Choices for the status field STATUS_CHOICES = [ ('CANCELLED', 'Cancelled'), ('LIVE', 'Live'), ('SCHEDULED', 'Scheduled'), ('POSTPONED', 'Postponed'), ('FINISHED', 'Finished'), ] name = models.CharField(verbose_name="Event name", max_length=30) slug = models.SlugField(verbose_name="Slug", max_length=30) sport = models.ForeignKey(Sport, on_delete=models.CASCADE) country = models.ForeignKey(Country, on_delete=models.CASCADE, related_name="events") competition = models.ForeignKey(Competition, on_delete=models.CASCADE, related_name="events", null=True) competitors = models.ManyToManyField(Competitor, through='EventCompetitor', through_fields=('event', 'competitor')) status = models.CharField(verbose_name="Status", max_length=10, choices=STATUS_CHOICES, default='SCHEDULED') start_date = models.DateTimeField(verbose_name="Start date", null=True, blank=True) venue = models.CharField(verbose_name="Venue", max_length=60, blank=True, null=True) city = models.CharField(verbose_name="City", max_length=80, blank=True, null=True) class Meta: verbose_name_plural = "Events" def __str__(self): return self.name admin.py @admin.register(Event) class EventAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("name",)} list_display = ("name", "slug", "country", "sport") list_filter = … -
Optimizing Django Social Media App: Efficient Handling of Profile Privacy and Pagination Logic for Post Retrieval
I am new to Djnago and I am designing my first Social Media App, so I am a bit new to this. I have an API view to get a users profile and their posts. I have implemented logic to check if the requesting user is able to view another users posts based on their profile_privacy and if the requesting user follows them or not. If the requesting user is able to view the users posts, then and only then we query for their posts. My question is: Since the posts are paginated, when the user requests for the profile, it will perform the logic and then get the appropriate posts, however, when we query for the second page of Post data, it will perform the same logic and checks again (check the follow instance to see if the requesting user follows them). Instead of performing this logic for every page query, is there a way to check it only once since for all other page requests we know the user already follows them? One approach was checking if the page being requested is the first page and only perform the checks for that, but that introduces security issues since … -
Getting Origin is not allowed by Access-Control-Allow-Origin when using Django authentication on one url but all origins are allowed
I am running into issues with CORS on Django and React (fetch). Django is set up like this: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rest_framework", "corsheaders", "users", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "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", ] CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] CORS_ORIGIN_WHITELIST = ( "http://localhost:3000", "http://127.0.0.1:3000", ) The urls in users: urlpatterns = [ path('login/<str:username>/<str:password>/', login), path('logout/', logout), path('info/', info), ] and views from rest_framework.decorators import api_view from rest_framework.response import Response from django.contrib import auth from django.http.response import HttpResponse # Create your views here. @api_view(['GET']) def login(request, username, password): user = auth.authenticate(username=username, password=password) if user is not None: auth.login(request, user) return Response('yes') else: return Response('no') @api_view(['POST']) def logout(request): auth.logout(request) return Response('hmmmmmmm') @api_view(['GET']) def info(request): if request.user.is_authenticated: return HttpResponse('wow, this is really critical information: 5!') else: return HttpResponse('nothing here...') When I do a request from react let [message, setMessage] = useState('waiting...') fetch('http://localhost:8000/users/login/Timoty/foo') .then(res => res.text()) .then(text => setMessage(text)) I get the typical error... What puzzles me the most is the fact that this is a cors issue, I am thinking that maybe I need to do some cookie magic from my react code, but why am I getting cross origin errors then? It … -
Change django.forms.models.ModelChoiceIterator
The choices variable of one of my fields (django.forms.models.ModelChoiceIterator) in ModelForm contains 3 items. In some cases, I want to use only one of them (the first one in the "list") for the actual HTML. Here's a part of the Django Python code: class MyForm(ModelForm): def __init__(self, *args, user=None, **kwargs): choices = self.fields['xxx'].choices qs = choices.queryset qs = qs[:1] ... ... self.fields['xxx'] = forms.ChoiceField( label="xxx", widget=forms.Select( attrs={ 'class': 'form-select' } ), self.fields['xxx'].choices = choices self.fields['xxx'].choices.queryset = qs class Meta: ... model = MyModel fields = ('xxx') ... This throws an error : 'list' object has no attribute 'queryset'" and, obviously, the size and content of choices do not change. choices is an instance of django.forms.models.ModelChoiceIterator How can I reduce the number of items in the choices which will be displayed in the HTML ? -
OSError: /home/ahmad/miniconda3/envs/python3.6/bin/../lib/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /lib/libgdal.so.30)
Title: Error in Miniconda Virtual Environment on Ubuntu 22.04 Description: I recently upgraded my Ubuntu system from 20.04 to 22.04 and encountered an issue my project was running smoothly on Ubuntu 20.04, but after the upgrade, I'm facing the following error: ruby Copy code OSError: /home/ahmad/miniconda3/envs/python3.6/bin/../lib/libstdc++.so.6: version `GLIBCXX_3.4.30' not found (required by /lib/libgdal.so.30) I have tried several solutions I found online, including installing build essentials, Python development headers, and even creating a new virtual environment, but the issue persists. Here are some key details: I'm using Miniconda to manage my Python environment. I have created a virtual environment with Python 3.6 for my Django project. I would greatly appreciate any guidance or solutions to resolve this issue and successfully install GDAL in my virtual environment on Ubuntu 22.04. Thank you for your help! -
Getting Error cors "Request header field responsetype is not allowed by Access-Control-Allow-Headers in preflight response" in django
Error in the browser console Access to XMLHttpRequest at 'https:///some_site/resource1/downloadCSV' from origin 'https://some_site' has been blocked by CORS policy: Request header field responsetype is not allowed by Access-Control-Allow-Headers in preflight response. check the API Method @api_view(["POST"]) def downloadCSV(request): request_body = request.data response = HttpResponse( some_service.call_some_other_service(), content_type="application/octet-streamf", ) today = datetime.today().strftime("%Y-%m-%d") filename = f"{today}_Data.csv" response["Content-Disposition"] = f'attachment; filename="{filename}.csv"' return response main/settings.py INSTALLED_APPS = [ ............. "corsheaders", ........ ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", ] CORS_ORIGIN_ALLOW_ALL = True I can't do it because the other response type header is failing, Please suggest how to allow the responseType =bob so that I will able to download API. CORS_ALLOW_HEADERS = [ # ... 'responsetype', # ... ] -
winerror 5 access denied
i am setting up a virtual environment for django and when i use python -m venv djangoenv a winerror 5 pops up to tell me acess denied please i need help with this. i have been trying the whole day with different versions of vscode and i get the same message. i dont know if it has something to do with the path or i am not just during it right.i am a beginner and i can't seem to spot what exactly the problem is -
Creating and saving a model object with a calculated m2m field Django
New to Django, I don't know if it's still worth it. I'm currently trying to save a model form with a many-to-many field that should be set randomly according to other fields(category, subcategory, number) in the same form. how do I get it to work? class Exam(models.Model): categ=models.ManyToManyField(Category,blank=False) sscateg = models.ManyToManyField(SubCategory,blank = True,null= True) question = models.ManyToManyField (Question,related_name='questionsEx',blank=False) nbquestion = models.IntegerField() def save(self, *args, **Kwargs): super(Exam, self).save(*args,**Kwargs,commit=False) if self.pk: qs=Question.objects.filter(category=self.categ).filter(sscateg=self.sscateg).values_list('id',flat =True) questions = random.sample(qs,self.nbquestion) for quest in questions: self.question.add(quest) super(Exam, self).save(*args,**Kwargs) forms.py class ExamForm(forms.ModelForm): nbquestion = forms.IntegerField(required = False) categ=forms.ModelChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple,required = False) sscateg=forms.ModelChoiceField(SsCategory.objects.all(), widget=forms.CheckboxSelectMultiple,required=False) def save(self, commit=True): instance = forms.ModelForm.save(self, False) self.save_m2m() instance.save() return instance views.py class ExCreateView(LoginRequiredMixin, CreateView): login_url = 'login' template_name = 'MakeEx.html' model = Exam form_class = ExamForm success_url = reverse_lazy('Exams') def form_valid(self, form): instance=form.save(commit=False) instance.save() form.save_m2m() return super(ExCreateView,self).form_valid(form) -
image path is incomplete django
in my-projet (django) The image path is incomplete in some api How can i fix it like when i use this api (categories) i got this Response Note that the image path is complete [ { "id": 1, "name_ar": "تطبيقات توصيل", "name_en": "weew", "icons": "http://127.0.0.1:8000/media/catecgorys/cloud123333_ZCE0xex.svg" }, { "id": 2, "name_ar": "متاجر", "name_en": "stores", "icons": "http://127.0.0.1:8000/media/catecgorys/cloud123333_BSbQU6b.svg" }, ] but when i use some api the entire image path is not displayed like how i can fix it ? { "status": "True", "data": [ { "id": 1, "code": "444", "percentage": "10%", "store": { "id": 1, "name_ar": "", "name_en": "noon", "description": "sdsdsdsdsdsdsd", "url": "noon.com", "logo": "/media/logo/Noon_log.jpeg", "categories": [ { "id": 1, "name_ar": "category 1", "name_en": "category 1", "icons": "/media/Categories/cloud123333.svg" } ] }, "description": "", "type": "", "ratings": { "id": 2, "likes": 1, "dislikes": 1 } } ] } my code : class GetCouponsByCategoryAPIView(viewsets.ModelViewSet): permission_classes = [permissions.AllowAny] queryset = Coupons.objects.all() serializer_class = CouponsSerializer def post(self, request, *args, **kwargs): categorys_id = request.data.get("Categories_id") if not categorys_id: return Response({"error": "Categories_id parameter is required."}, status=status.HTTP_400_BAD_REQUEST) try: category = Categories.objects.get(id=categorys_id) stores = Stores.objects.filter(catecgorys=category) except Categories.DoesNotExist: return Response({"status": "False", "error": "Category not found."}, status=status.HTTP_404_NOT_FOUND) except Stores.DoesNotExist: return Response({"status": "False", "error": "Store not found."}, status=status.HTTP_404_NOT_FOUND) coupons = Coupons.objects.filter(store__in=stores) serializer = CouponsSerializer(coupons, … -
Unable to capture record IDs for Bulk Updating Fields for non-admin users in Django Front End
I'm trying to bulk update fields for a list of records, similar to an Admin Actions type drop down list , for non-admin users in the front end. The process a user follows - Step 1. Come to the candidates.html page Step 2. Select the candidate to whose field is to be updated by selecting the check box of the respective candidate in the candidates.html page which has the table of the candidates and the first column as the check box for selection. Step 3. Click on the mass_update_candidates button to be directed to the mass_update_candidates.html to update the fields with the new value. Step 1 & 2 function correctly, when clicking on the mass_update_candidates button it redirects to the page, however, On clicking Update Button, it is not capturing the selected IDs Please advise. Below are the forms.py, views.py and the different html templates. I do not have any coding experience. I'm trying to learn. This is a pet project I've created to learn. Any help is most appreciated. If you know of a better method to achieve this please do let me know, I'm more than willing to try new ideas. Thank You! Browser Console Message: JavaScript is … -
Why is django query set .filter() only accepting an id / interger, when I want to filter by a field/value?
I am new to django, creating a blog / article sharing website. I have a few databases set up, CRUD is functioning but I'm having trouble getting a bit more creative with the site. For example, on the news articles page, it lists all the articles shared by users. It states the category, the user, the title, the external link and when it was shared. Instead of just listing all of them , I would like to be able to give the user an option to filter either by user who submitted (all articles submitted by admin) or by car I'm trying to filter a database, by the value of one of its fields. So for example I have a model News which has fields like title, website, user, created on . class Article(models.Model): category = models.CharField(max_length=25, null=True) def __str__(self): return self.category class News(models.Model): title = models.CharField(max_length=100, null=True) website = models.CharField(max_length=50, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(auto_now_add=True) likes = models.ManyToManyField( User, related_name='link_like', blank=True) external_link = models.URLField() category = models.ForeignKey(Article, on_delete=models.CASCADE) class Meta: ordering = ["-created_on"] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() These are passed in from the user in a form when they share a news … -
How do I migrate my current users to aws cognito
I'm in the process of migrating my user authentication system to AWS Cognito. I followed this tutorial here and I can now send the Bearer token to django and it is stored as a user with the username containing the unique sub. The issue I am facing now is, I already have quite a large number of users that are signed up using my previous system, which was a token based authentication method. My question now is, how do I migrate those users to aws cognito, or is there a way to allow sign-ins using both aws cognito and also the token based authentication. Also note that, the user model have relationship with other models; so deleting or removing a user will also delete those data tied to a user. By the way, I am using react and amplify for the frontend authentication. -
Django models dependencies
I am new at Django Python. Need help I am writing Calory Counter. I have models Food (list of foods with calories, etc), Profile (store all selected foods through model Postfood) and Recipes. The question is how I can add recipe to my ration (Profile) . My models: class Food(models.Model): name = models.CharField(max_length=200, null=False) measure = models.CharField(max_length=200, null=True) quantity = models.PositiveIntegerField(null=False, default=0) calorie = models.FloatField(null=False, default=0) carbohydrate = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) fats = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) protein = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) recipe = models.ForeignKey('Receipe', null=True, on_delete=models.CASCADE) class Receipe(models.Model): name = models.CharField(max_length=200) content = models.CharField(max_length=1000000) portion = models.PositiveIntegerField(default=1, null=False) calorie = models.IntegerField(default=0, blank = True) carbohydrate =models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) fats = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) protein = models.DecimalField(max_digits=5, decimal_places=2, default=0, null=True) time = models.PositiveIntegerField(default=20, blank=True) difficulty_level_options = ( ('easy', 'easy'), ('medium', 'medium'), ('difficult', 'difficult')) difficulty_level = models.CharField(max_length=50, choices=difficulty_level_options, default='medium') ingredients = models.TextField(max_length=1000000, null=True, blank=True) img_url = models.ImageField(upload_to='static/recipes', null=True, blank=True, default='static/recipes/no image.jpeg') class Profile(models.Model): person_of = models.ForeignKey(User, null=True, on_delete=models.CASCADE) current_weight = models.IntegerField(default=0, blank=True) goal_weight = models.IntegerField(default=0, blank=True) calorie_count = models.FloatField(default=0, blank=True) food_selected = models.ForeignKey(Food, on_delete=models.CASCADE, null=True, blank=True) exercises_selected = models.ForeignKey(Exercise, on_delete=models.CASCADE, null=True, blank=True) time_hour_exercise = models.IntegerField(default=0, blank=True) calorie_exercise = models.FloatField(null=False, default=0) quantity = … -
django import export not import excel file with foreignkey msssql
i have a resource.py class bankid_resource(resources.ModelResource): class Meta: model = bankID and have model.py class bankID(models.Model): bankIdN = models.CharField(max_length=300, null=True, blank=True, unique=True) userID = models.ForeignKey('UserDetails', on_delete=models.CASCADE, null=True, blank=True) CardN = models.CharField(max_length=300, null=True, blank=True, unique=True) and in my view.py iwant to import excel file with this function def import_bankid_list(request): if request.method == 'POST': bankids = bankid_resource() dataset = Dataset() new_bankids = request.FILES['myFile'] data_import = dataset.load(new_bankids.read()) result = bankids.import_data(dataset, dry_run=True) if not result.has_errors(): bankids.import_data(dataset, dry_run=False) return redirect('import_bankid_list') else: return redirect('') return render(request, 'personel/import.html') but data not import because have a ForeignKey in exported csv file. my database is mssql. i need help to solve the problem any file without ForeignKey will import corecctly. -
The appearance of the admin panel in Django is broken
I am a Django beginner. When I enter the address of the admin panel, I encounter a broken and strange panel: https://s6.uupload.ir/files/screenshot_2023-09-02_155801_0mvm.png -
Not registering logged in user's information into form (Django/Javascript)
I am trying to fill in the logged in user's Name and Email into a a form for a POST request. It is for a an ecommerce website for when they click the Make Payment button, but it keeps coming up withnull for the fields. I think this is why it won't send the request through. I am trying to grab their already registered Name and Email so they won't have to fill them in again. This is my code: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> <div id="user-info"> <div class="form-field"> <input required class="form-control" type="text" name="name" placeholder="Name" /> </div> <div class="form-field"> <input required class="form-control" type="email" name="email" placeholder="Email" /> </div> </div> <div id="shipping-info"> <hr /> <p>Shipping Information:</p> <hr /> <div class="form-field"> <input class="form-control" type="text" name="address" placeholder="Address" /> </div> <div class="form-field"> <input class="form-control" type="text" name="city" placeholder="City" /> </div> <div class="form-field"> <input class="form-control" type="text" name="county" placeholder="County" /> </div> <div class="form-field"> <input class="form-control" type="text" name="postcode" placeholder="Postcode" /> </div> </div> <hr /> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue" /> </form> </div> <br /> <div class="box-element hidden" id="payment-info"> <small>Paypal Options</small> <button id="make-payment">Make Payment</button> </div> </div> <div class="col-lg-6"> <div class="box-element"> <div class="box-element"> … -
Intersection of QuerySet and list of objects
Assume that I have a query set of Product model. products_qs = Product.objects.filter(...) products_list = [<Product 1>, <Product 5>] How can I detect intersection of products_qs and products_list? -
Django returning 500 status code instead of 404 for a not found resources
In my Django project whenever I turn DEBUG to False all my 404 resource not found errors, returns as 500 internal server error. I also don't get a stack trace in my log file for the cause of the error. I just only get internal server error with status code 500. But if DEBUG is set to true, it works fine and I get a 404 not found code for a resource not found error Even some of my static files and images that were not found are all returning 500 internal server error. This happens only when debug is false Works fine when debug is set to true. I read online where allowed host must be set to the actual host and not a "*". I have done all this but it is still not working. I am still getting 500 status code for a resource not found error and no stack trace. I'm using Django 4 python 3.9 -
Django Website Not Displaying Expected Content
I'm new to Django and am building a site for reminders. However, I see a blank page on launch. My base.html has a form for reminders and a display section, index.html has a similar form, and styles.css is for styling. Static paths seem fine, server runs with no errors, and migrations are updated, but still no content. Here's my code: `base.html Reminder FormSet Reminder{% csrf_token %}{{ form.as_p }}Set ReminderReminders{% for reminder in reminders %}{{ reminder.time }} - {{ reminder.title }}: {{ reminder.message }}{% endfor %} ` index.html <form method="post">{% csrf_token %}{{ form.as_p }}<button type="submit">Set Reminder</button></form> styles.css *{margin:0;padding:0;box-sizing:border-box;}body{font-family:'Arial',sans-serif;background-color:#3618bb;color:#4c34a3;}.container{max-width:1200px;margin:0 auto;padding:20px;}h1,h2,h3{margin-bottom:20px;}input[type="text"],input[type="submit"]{padding:10px;margin-bottom:10px;}input[type="submit"]{cursor:pointer;background-color:#333;color:#8b1818;border:none;} Any ideas what's wrong? -
embed video on website using django-embed-video
when run it gives an error: Exception Type: TemplateDoesNotExist at / Exception Value: video.html and also: return render(request,'video.html',{'obj':obj}) views.py: from django.shortcuts import render from .models import Item def video(request): obj = Item.objects.all() return render(request,'video.html',{'obj':obj}) video.html: {% load embed_video_tags %} <!doctype html> <html lang="ru"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Демо Bootstrap</title> </head> <body> <h1>Привет мир!</h1> {% block content %} {% for i in obj %} {% video i.video 'small' %} {% endfor %} {% endblock %} </body> </html> I searched how to fix the error on YouTube and did not find anything