Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ajax filters displays all data but does not filter. DJANGO AJAX
i'm using ajax filtering to filter my products by color, brand, size. The data filtering successfully but it shows everything. I'm hoping for your help and thank you for your attention Trying to filter products... product-filter.js:20 {data: '\n\n \n <div class="col-md-4 mb-0">\n … </div>\n </div>\n </div>\n \n'}data: "\n\n \n <div class=\"col-md-4 mb-0\">\n[[Prototype]]: Object product-filter.js:21 Data filtered successfully ajax $(document).ready(function(){ $(".filter-checkbox").on('click', function(){ let filter_object = {}; $(".filter-checkbox").each(function(index,ele){ let filter_value = $(this). val(); let filter_key=$(this). data('filter'); filter_object[filter_key]=Array.from(document.querySelectorAll('input[data-filter='+filter_key+']:checked')).map(function(element){ return element.value; }); }); $.ajax({ url:'/filter_products', data:filter_object, dataType:'json', beforeSend:function(){ console.log('Trying to filter products...'); }, success:function(response){ console.log(response); console.log('Data filtered successfully'); $("filteredProducts").html(response.data) } }); }); }); views.py def filter_products(request): color = request.GET.getlist('color[]') brand = request.GET.getlist('brand[]') size = request.GET.getlist('size[]') products = Product.objects.all().order_by('-id').distinct() if len(color)>0: products=products.filter(color__id__in=color).distinct() if len(brand)>0: products=products.filter(brand__id__in=brand).distinct() if len(size)>0: products=products.filter(size__id__in=size).distinct() t = render_to_string('ajax/product-list.html',{'products':products}) return JsonResponse({'data':t}) def search(request): data1 = wishData(request) wishItems = data1['wishItems'] data = cartData(request) q = request.GET['q'] cartItems = data['cartItems'] products = Product.objects.filter(name__icontains=q).order_by('id') context = {'products': products, 'cartItems': cartItems,'wishItems': wishItems} return render(request, 'store/store.html', context) def product_view(request, id): product = Product.objects.filter(id=id).first() data = cartData(request) cartItems = data['cartItems'] data1 = wishData(request) wishItems = data1['wishItems'] context = {'product':product, 'cartItems':cartItems, 'wishItems':wishItems} return render(request, 'store/product_view.html', context) def store(request): data1 = wishData(request) wishItems = data1['wishItems'] data = cartData(request) cartItems = data['cartItems'] … -
Why does my dependent dropdown form act up?
I am attempting to implement a dependent dropdown form for my project. I want the makes dropdown to be dependent of the year of the vehicle. The models dropdown entries should be dependent on the year and make dropdown entries selected. Finally, the repairs dropdown should be dependent on the year, make, and model selected. However, this is not the case. In my django database, I have two entries titled "Chevrolet" that are connected to years 1980 and 1981 via ForeignKey. Both of these entries are connected to an entry titled "Camaro". Another entry I have stored in my backend database has 1981 as the year, "Ford" as the make (connected to 1981 via ForeignKey), and "LTD Crown Victoria" and "F-150" as models. While the year and makes appear as they should, the other entries do not. I can only get the appropriate models to appear in the dropdown box after I select 1981 as the year and "Ford" as the model. Afterwards, I am able to see the models connected with the 1981 entry for "Chevrolet". Code from my Home.html file {% load static %} <!doctype html> <html lang="en"> <link rel="stylesheet" href="{% static 'css/edits.css' %}"> <head> <meta charset="UTF-8"> <meta … -
Completing and order using choice fields
I am trying to make it so when an order processed and payment is made, the payment status is changed to complete. At the moment my orders stay on pending consistently. What should be happening is that the order is completed the page is redirect to home page, cart is emptied and payment status changes to 'Complete' Models: class Order(models.Model): PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] customer = models.ForeignKey( Customer, on_delete=models.PROTECT, null=True, blank=True) order_id = models.IntegerField(null=True) order_date = models.DateTimeField(auto_now_add=True) payment_status = models.CharField( max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING ) def __str__(self): return str(self.id) @property def get_cart_items(self): order_items = self.orderitem_set.all() total = sum([item.quantity for item in order_items]) return total @property def get_cart_total(self): order_items = self.orderitem_set.all() total = sum([item.get_total for item in order_items]) return total views: if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, payment_status='P') #TODO: add float field? total = data['form']['total'] order.order_id = order_id if total == order.get_cart_total: order.payment_status = 'C' order.save() JS var total = '{{order.get_cart_total}}' var form = document.getElementById('form') form.addEventListener('submit', function(e){ e.preventDefault() console.log('Form Submitted..') document.getElementById('form-button').classList.add('hidden'); document.getElementById('payment-info').classList.remove('hidden'); }) document.getElementById('make-payment').addEventListener('click', function(e){ submitFormData() }) function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'first_name':null, 'last_name':null, 'email':null, 'total':total, } var url = … -
django channels work fine locally but fail on server
I have a simple chat application using django and django-channels. I was follow django-channels tutorial. It work fine locally but in production it failed. this is my js code for websocket initial: const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); this is error that raise when im goint to chat page: Mixed Content: The page at 'https://site-url.ir/chat/room/1/' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://site-url.ir/ws/chat/room_1/'. This request has been blocked; this endpoint must be available over WSS. room.js:18 Uncaught DOMException: Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS. I dont know what can i do for fix this bug. -
Django - combining querysets from different models and serializing them
I am a newbie trying to build an e-commerce website for fun. Firstly, I take the query parameters from the url, then find the fitting products and then try to find the corresponding images. However I cannot find a way to: combine a queryset of products and a queryset of images (connected with each other by a foreign key) serialize them into a JSON, to show on the frontend I am using postgresql. Sample url http://localhost:3000/products/?slider=%5B500%2C8000%5D&service=1&stars=%5B3%2C4%2C5%5D models.py class Hotel(models.Model): name = models.CharField(max_length=200, unique=True) location = models.CharField(max_length=200) price_per_person = models.FloatField() service = models.PositiveSmallIntegerField() stars = models.PositiveSmallIntegerField() description = models.TextField() class Image(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to='images', null=True) views.py @api_view(["GET"]) def getProductsView(req): productsSet = Hotel.objects.all() for key, value in req.GET.items(): value = json.loads(value) if key == "stars": orStatement = Q(stars=value[0]) for star in value[1:]: orStatement = orStatement | Q(stars=star) productsSet = productsSet.filter(orStatement) elif key == "slider": productsSet = productsSet.filter(price_per_person__range=(value[0], value[1])) else: productsSet = productsSet.filter(**{key: value}) productsSet = productsSet[:25] imageSet = Image.objects.filter( hotel_id__in=[i for i in productsSet.values_list("id", flat="True")] ) # Tried # productsSet.union(imageSet) # but the result didn't change serializer = HotelSerializer( productsSet, context={"request": req}, many=True ) return Response(serializer.data) I tried calling django's union, but to no avail and I … -
Django reverse accessor clash - multiple uses of a model
I have two models, Photo and Story. The Story model uses the Photo a couple different ways - for a thumbnail, a header photo, and a gallery. I am storing an optional Story reference in the Photo model. This was causing a E.304 error: (fields.E304) Reverse accessor for 'stories.Story.header_image' clashes with reverse accessor for 'stories.Story.thumbnail'. I added related_name='+' to both the thumbnail and header_image fields. This disallows the backward relation and got rid of my reverse accessor clash issue. I was able to set up a PhotoInline in the Django admin, but also realized that there is now no way for a user to add a thumbnail or header_image inline - the typical "edit" and "add" options aren't available. What do I need to change about my models or admin config to allow for that? I tried changing the related_name params to name the relationships instead of disallowing them, but that didn't seem to help - not sure if I would need to use those values somewhere. class Story(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) thumbnail = models.ForeignKey('Photo', on_delete=models.CASCADE, null=True, blank=True, related_name='+') header_image = models.ForeignKey('Photo', on_delete=models.CASCADE, null=True, blank=True, related_name='+') content = tinymce_models.HTMLField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = … -
Validate Model wasn't added to m2m field in another Model yet
I have 2 models: class UserInventory(models.Model): user = models.OneToOneField(verbose_name='user', to='users.User', on_delete=models.CASCADE) # items promocodes = models.ManyToManyField(verbose_name="promos", to="inventory.PromocodeItem", blank=True) class PromocodeItem(models.Model): name = models.CharField(verbose_name='code name', max_length=128) code = models.CharField(verbose_name='code', max_length=512, db_index=True) is_used = models.BooleanField(verbose_name='used?', default=False) My API can add codes to the user_inventory model. I want to create a manual admin APIView to give codes to users. In this view, I also want to check if this code already exists in anyone's inventory. I have this code: def post(self, request, code_id, user_id): code = PromocodeItem.objects.filter(id=code_id).first() user = User.objects.filter(id=user_id).first() inv = UserInventory.objects.get_or_create(user=user) // Here I need to validate that the code model has not been added to anyone`s user inventory yet. inv.promocodes.add(code) return Response("ok") Which is the best way to do this? -
unable to represent IMG in CSS and HTML
enter image description here I want to do coffee Store, when you look at Background.png in file section It's red, I have no idea why, but this is a problem. -
Uploading a .YAML file using Django and reading it's contents to display a graph/plot on the webpage
I want to be able to upload .yaml files using the Django Admin interface and then access the content of that file to do preprocessing and outputting a graph using plotnine on the webpage. Example code of preprocessing and plotting a graph: import yaml import pandas as pd import numpy as np import plotnine as p9 slurm_data = {} with open('slurm-22.05.5-02_27_2023-16_33_29.yaml', 'r') as f: all_slurm_data = yaml.load_all(f, yaml.FullLoader) for d in all_slurm_data: for k,v in d.items(): slurm_data[k] = v time_window = 60 data_frames = [] for slurm_partition_name, slurm_partition_data in slurm_data.items(): data_frames.append(pd.DataFrame.from_dict(slurm_partition_data)) data_frames[-1]['node_type'] = slurm_partition_name data_frames[-1]['days_scheduled'] = np.random.randint(0,time_window, size=len(data_frames[-1])) data_frames[-1]['days_free'] = time_window - data_frames[-1]['days_scheduled'] data_frames[-1]['projected_utilization'] = data_frames[-1]['days_scheduled'] / float(time_window) slurm_data_frame = pd.concat(data_frames) slurm_data_frame.hist(bins=30) -
configure Django settings for static files with Heroku
I am trying to deploy my Django website using Heroku. So far the site has deployed successfully but the only problem is collecting the static files. I am stuck with how I am supposed to configure my settings.py file so that the website knows where to find these static files. folder structure -website ---App ------Static ---------App ---Website ---staticfiles ---manage.py ---Procfile ---requirements.txt ---runtime.txt settings.py DEBUG = False BASE_DIR = Path(__file__).resolve().parent.parent MIDDLEWARE = [ ... "whitenoise.middleware.WhiteNoiseMiddleware", ... ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), os.path.join(BASE_DIR, "App/static") ] django_heroku.settings(locals()) STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" error msg whitenoise.storage.MissingFileError: The file 'App/static/app/styling-images/search_button.png' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x0000016932C5D190>. The CSS file 'App\styles.css' references a file which could not be found: App/static/app/styling-images/search_button.png Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. -
How to Create data with read_only_fields in Django Rest Framework
and facing a issue with read_only fields suppose I have the follwoing serailizer `class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] read_only_fields = ['account_name']` where the account_name (in the Account model this field can not be null) is set to read_only because I do not want to update its data after creation but while creating the data using I am passing the account_name in the serializer but its excluding the account_name and giving the error "account_name" can not be null can anyone give me the solution for this how I can create a data with read_only field which can not be null I have tried to remove it from read_only_field but by doing this the account_name can be update but I don't want to update it after creation -
How to update status of Celery's tasks in Django?
Friends I have a question: I want to update the status of celery's tasks in Django. An example of what I want: 1- Create a task in tasks say to extract numbers from multiple text files: @shared_task() def text_analysis(): #Do this and that 2- Create a function in views to upload the files: def text_analysis(request): if request.method == 'POST': text_files = request.FILES.getlist("files") for text in text_files: text_analysis.delay() return render(request,"demo_demo.html",{"files":files}) 3- Create a HTML template to view the results: <main> <form method = "POST" enctype = "multipart/form-data" id = "texts_form"> {% csrf_token %} <input name="files" type = "file" multiple > <button type = "submit"> Submit </button> </form> <div class="table-data"> <div class="order"> <div class="head"> <h3>Recent Text Files</h3> </div> <table> <thead> <tr> <th>Name</th> <th>Creating Date</th> <th>Status</th> </tr> </thead> <tbody> <div> {% for file in files %} <tr> <th> file name </th> <th> file status. ->>>>>>>>>> What I want to do!!!! </th> </tr> {% endfor%} I tried many methods like the following: https://github.com/IbrahemKandel/python-dontrepeatyourself-django-celery-result-backend/blob/main/core/templates/home.html https://github.com/testdrivenio/fastapi-celery/blob/master/project/static/main.js -
504 Gateway Timeout in Kubernetes Deployed Django Application with Nginx Ingress
I am facing a 504 Gateway Timeout issue with my Django application deployed on Kubernetes. The application is running behind an Nginx ingress controller. My longer running requests keep timing out after 1 minute exactly. I'm not sure what could be causing the issue as i've altered the timeouts. My Ingress resource has the following annotations: Annotations: ingress.kubernetes.io/proxy-body-size: 100m ingress.kubernetes.io/proxy-connect-timeout: 1000 ingress.kubernetes.io/proxy-read-timeout: 1000 ingress.kubernetes.io/proxy-send-timeout: 1000 ingress.kubernetes.io/send-timeout: 1000 ingress.kubernetes.io/uwsgi-read-timeout: 1000 Additionally, I have the following Nginx ConfigMap settings: allow-snippet-annotations: "true" client-max-body-size: 100m hsts-max-age: "1" max-fails: "100" proxy-buffering: "off" proxy-connect-timeout: 610s proxy-read-timeout: 600s proxy-send-timeout: 300s uwsgi_connect_timeout: 600s worker-shutdown-timeout: 86400s I run Django using gunicorn like this: /usr/local/bin/gunicorn config.wsgi -w 2 -b 0.0.0.0:5000 --chdir=/app --timeout 1000 --limit-request-line 0 The application works fine locally and doesn't have any performance issues. I have tried increasing the timeouts and resources for the application, but the issue persists. I would appreciate any suggestions on how to resolve the 504 Gateway Timeout error or any tips on how to further debug this issue. -
acess services.py from a model Manager
I created a services.py file on the root directory of an app called mymoney and I plan to add helper functions there to keep my models.py file with simpler language. Now I wonder, how can I access functions and methods inside the services.py from the a model Manager? models.py from django.db import models from datetime import date class Balance(models.Model): date = models.DateField(auto_now_add=True) account = models.ForeignKey('mymoney.account', on_delete=models.CASCADE) amount = models.DecimalField(max_digits=15,decimal_places=2) objects = BalanceManager() class Meta: app_label = "mymoney" Manager (a continuation of models.py, that's why no imports) class BalanceManager(models.Manager): def balance_inconsistences(balance_dates: dict, initial_date: date, today: date) -> tuple: # return tuple with two lists: return of first wrong_balance_dates() # and second return of dates_missing_balance_consolidation() wrong_dates = wrong_balance_dates(balance_dates, initial_date) dates_missing = dates_missing_balance_consolidation(balance_dates, initial_date, today) return wrong_dates, dates_missing services.py from mymoney.models import Balance from datetime import date from calendar import monthrange def end_month_dates_since_first_transaction(initial_date: date, today: date) -> list: pass def wrong_balance_dates(balance_dates: dict, initial_date: date) -> list: pass def dates_missing_balance_consolidation(balance_dates: dict, initial_date: date, today: date) -> list: pass -
django 4: type object 'Post' has no attribute 'published'
database is ok, migrations created problems with it **object_list = Post.published.all() ** Post: class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') Views: def post_list(request): object_list = Post.published.all() paginator = Paginator(object_list, 3) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, 'blog/post/list.html', {'page': page, 'posts': posts}) Migrations: class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=250)), ('slug', models.SlugField(max_length=250, unique_for_date='publish')), ('body', models.TextField()), ('publish', models.DateTimeField(default=django.utils.timezone.now)), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('status', models.CharField(choices=[('draft', 'Draft'), ('published', 'Published')], default='draft', max_length=10)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='blog_posts', to=settings.AUTH_USER_MODEL)), ], ), ] urls main app: urlpatterns = [ re_path(r'^admin/', admin.site.urls), re_path(r'^blog/', include(('blog.urls', 'blog'), namespace='blog')), ] urls blog app: urlpatterns = [ # post views re_path(r'^$', views.post_list, name='post_list'), re_path(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), ] first time per stack overflow, sorry for the mistakes registered in the database column "published". idk what's the problem -
Field 'id' expected a number but got 'filter_data'. DJANGO, AJAX
I am working on filters in my project. Based on the tutorial, I started adding Ajax so that I could filter cards by several categories. Everything was working fine until I added the data and jsonResponse. Now every time I click the checkbox I get this error Ajax $(document).ready(function(){ $(".axaLoader").hide() $(".filter-checkbox").on('click', function(){ var _filterObj={}; $(".filter-checkbox").each(function(index,ele){ var _filterVal=$(this). val(); var _filterKey=$(this). data('filter'); _filterObj[_filterKey]=Array.from(document.querySelectorAll('input[data-filter='+_filterKey+']:checked')).map(function(el){ return el.value; }); }); $.ajax({ url:'filter_data', data:_filterObj, dataType:'json', beforeSend:function(){ $(".ajaxLoader").show(); }, success:function(res){ console.log(res); $("#filteredProducts").html(res.data); $(".ajaxLoader").hide(); } }); }); }); views.py def filter_data(request): return JsonResponse({'data':'hello'}) urls.py from django.urls import path, include from django.contrib.auth.views import PasswordChangeView from . import views from .forms import PasswordUpdateForm urlpatterns = [ path('', views.store, name="store"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('registration/', views.registrationPage, name="registration"), path('profile/', views.profile, name="profile"), path('change_password/', PasswordChangeView.as_view(template_name='store/change_password.html', success_url='profile', form_class=PasswordUpdateForm ), name="change_password"), path('change_password/profile/', views.profile, name="profile"), path('update_item/', views.updateItem, name="update_item"), path('update_wish_item/', views.updateWishItem, name="update_wish_item"), path('process_order/', views.processOrder, name="process_order"), path('<str:id>', views.product_view, name="product_view"), path('wishlist/', views.wishlist, name="wishlist"), path('search/', views.search, name="search"), path('filter_data/', views.filter_data, name="filter_data"), path('search/<str:id>',views.product_view, name="product_view"), ] Error Traceback (most recent call last): File "C:\Users\Admin\PythonProject 555\venv\lib\site-packages\django\core\handlers\exception.py", line 56, in inner response = get_response(request) File "C:\Users\Admin\PythonProject 555\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Admin\PythonProject 555\boots\store\views.py", line 118, in product_view product = Product.objects.filter(id=id).first() File … -
Failed to save Django formset with queryset
i have faced the problem in django formset, i want to update formset using function view, when this line formset = MyFormset(request.GET or None, instance=form_main, queryset=queryset) included cant save but if i remove instance=form_main, queryset=queryset) it does not populate data but i can add manually and save it. I want this formset to polulate from database and to save it back to database view.py form_main = get_object_or_404(MyModel, pk = pk) queryset = MyFormset.objects.order_by('item') if request.method == 'GET': form = MainForm(request.GET or None, instance=form_lpo) formset = MyFormsetForm(request.GET or None, instance=form_main, queryset=queryset) elif request.method == 'POST': formset = Grn_LineItemFormset(request.POST) form = MainForm(request.POST) if form.is_valid(): newmodel= NewModel.objects.create(................) -
Need to add custom forms based on User input
So basically I need to implement the following functionality In my django project, the admin should be able to select number of fields he needs and their type(textfield, radio buttons, etc.., mandatory fields and non mandatory fields ) for his form and based on this a new page with a form which has the aforementioned fields should be rendered. The admin should be able to add this as a backend script in django model. I tried a way out via Model forms but couldn't get a clear layout as to how should i use it. I am fairly new to this techstack. Any guidance would be helpful Thanks -
Django metadata returns blank?
I want to apply some metadata to a stripe-checkout. No errors. When the payment is done without errors, I am not able to collect the metadata again. The returned data is just blank like this {}. The checkOutSission-view looks like this: @csrf_exempt def createCheckoutSession(request): if request.method == 'POST': data = json.loads(request.body) product = data[0] option_back = data[1] option_legs = data[2] option_length = data[3] # Create a Stripe Checkout session session = stripe.checkout.Session.create( payment_method_types=['card'], line_items=[{ 'price_data': { 'currency': 'eur', 'product_data': { 'name': product, 'description': (f'Back: {option_back} | Legs: {option_legs} | Length: {option_length}'), 'quantity': 1, 'metadata': { 'option_back': option_back, 'option_legs': option_legs, 'option_length': option_length, }, }, 'unit_amount': 300, # in euro }, }], mode='payment', success_url='http://127.0.0.1:8000/configurator/success/?session_id={CHECKOUT_SESSION_ID}', cancel_url='http://127.0.0.1:8000/configurator/cancel/', ) return JsonResponse({'session_id': session.id, 'checkout_url': session.url}) else: return JsonResponse({'error': 'Invalid request method'}) The view that schould be called after the payement looks like this: def success(request): session_id = request.GET.get('session_id') session = stripe.checkout.Session.retrieve(session_id) items = session.get('customer_details') print(items.email) values = session.get('metadata') print(values) # Gjør noe med produktinformasjonen return HttpResponse("Success") Why do it not work like my predictions? I have tried to move the "metadata-block" in diffrent levels of the session-data-blocks. Nothing makes the wanted results. -
Django - Can't fetch Json data in javascript
Hello I am pretty new to Django and Javascript I want to build a simple application where users can write posts and see a list of all posts in reverse chronologial order on the index page. (The index page is rendered fine.) I created some Posts via the admin interface. Unfortunately I can't figure out why I am not able to fetch the JsonResponse and no div gets append to my template. the code looks as following: first I've created a Posts model class Posts(models.Model): text = models.TextField(max_length=512) timestamp = models.DateTimeField(auto_now=True) def serialize(self): return { "id": self.id, "text": self.text, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), } My view function to get all posts from the datatbase is called via path("get_posts", views.get_posts, name="get_posts"), and looks like this: @login_required def get_posts(): # get all posts posts = Posts.objects.all() # Return posts in reverse chronologial order posts = posts.order_by("-timestamp").all() return JsonResponse([post.serialize() for post in posts], safe=False) In my Javascript file (index.js) I want to load all Posts, create a div for each post and append them to my template document.addEventListener('DOMContentLoaded', function() { // By default, load_posts load_posts(); }); function load_posts() { // get posts from /posts API Route fetch('/get_posts') .then(response => response.json()) .then(posts … -
django.contrib.auth import get_user_model
I get an error in my User AttributeError: type object 'User' has no attribute 'objetcs' I get the error in forms.py when I try to use my User. // forms.py // from django import forms from django.contrib.auth import get_user_model from django.db import models from . import models User = get_user_model() class PerfilForm(forms.ModelForm): class Meta: model = models.Perfil fields = '__all__' exclude = ('usuario',) class UserForm(forms.ModelForm): password = forms.CharField( required=False, widget= forms.PasswordInput(), label='Senha' ) password2 = forms.CharField( required=False, widget= forms.PasswordInput(), label='Confirmar senha' ) def __init__(self, usuario=None, *args, **kwargs): super().__init__(*args, **kwargs) self.usuario = usuario class Meta: model = User fields = ('first_name', 'last_name', 'username', 'password', 'password2', 'email',) usuario_db = User.objetcs.filter(username=usuario_data).first() **<-- here I get the error** email_db = User.objetcs.filter(email=email_data).first() -
Django rest framework- blog post comment delete permission for admin user and owner user
does anyone know how to set delete permisssion for commented owner to delete the comment and for the admin user, delete all comments Serializers.py class DeleteCommentSerializer(serializers.ModelSerializer): class Meta: model = CommentModel fields = '__all__' Views.py class CommentDeleteView(generics.DestroyAPIView): permission_classes = [IsAdminUser,IsOwner] queryset = CommentModel.objects.all() serializer_class = DeleteCommentSerializer def perform_delete(self, serializer): serializer.save(user=self.request.user) Permissions.py class IsOwner(BasePermission): def has_permission(self, request, view): if request.method in ['PUT','DELETE']: return True return False def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True return obj.user == request.user -
How do I write a Django query that searches a nested JSON array?
I have the following JSON object (named 'data') on my Draft model: DRAFT1 data= { communications = [ {name: "john"}, {name: "bobby"} ] } DRAFT2 data= { communications = [ {name: "mark"}, {name: "erin"} ] } I'm guessing this is vaguely correct for a query, but I can't figure out the syntax for the '*'? Draft.objects.filter(data__communications__*__name__in=['john', 'erin']).count() How can I write a Django/Postgres query to return DRAFT1 and DRAFT2 as the result? -
AWS lightsail deployment Errors django
Good day, I have built a python / django webapp that i'm ready to deploy. I'm trying to deploy my webapp using AWS Lightsail, but the problem i'm facing is that my webapp will not load. I'm receving the error as follows:, but on my local Visual Studio code, but webapp is working just fine. What am i missing? My settings code is -
Point custom domain to a different website Django
I have a Django project deployed to a ubuntu server from digital ocean, using Apache as the web server and mod_wsgi, a custom domain name from Namecheap, and an SSL certificate. It has everything needed to be a solid website. But I also have a flask app deployed on an EC2 instance from AWS, besides changing the name servers on NameCheap to point to my EC2 instance, what else should I do for my domain to point to my Flask app instead of my Django app? Is it just as simple as removing the domain name from ALLOWED_HOST in Django settings.py? or is this more complex now that I have an SSL certificate? I hope it's not a meaningless question.