Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, "render" returns a POST request and not GET after a POST request
I'm having my view def my_wishlist(request): user = request.user user_products = WishlistProductPrices.objects.filter(user=user).all() ### Create filters ### filter = get_user_filter_fields_wishlist(user_products) filter = filter(request.GET,queryset = user_products) if request.method == "POST": post_form = MyForm(request.POST) if post_form.is_valid(): #do stuff form = MyForm() context = { "form":form, "filter":filter } return render(request, "myapp/add_wishlist.html",context=context) #Returns POST, seems like else: #invalid post_form context = { "form":post_form, "filter":filter } return render(request, "myapp/add_wishlist.html",context=context) else: #Get request form = MyForm() context = { "form":form, "filter":filter } return render(request, "myapp/add_wishlist.html",context=context) it works like a charm, but after the user has submitted something, and presses F5 the "do you want to resend the information again" pops-up. I find it weird, since I assume the render(request,"mypp/add_wishlist.html) ad the bottom of the page would return a GET request? -
My CSS files are not getting loaded from my S3 bucket, why?
Here's my S3 configurations: STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_QUERYSTRING_AUTH = False I have a couple of models that have ImageFields and when I upload an image it properly gets uploaded to my S3 bucket. But I also want to put my staticfiles there (JS, CSS). I have manually created a folder in the root of my S3 bucket called static and I have uploaded all of my CSS, JS files to that folder using S3's web app. However, in my template I am simply doing {% static 'css/main.css' %} and the file is not getting loaded. I used Chrome's inspect tool to check which resources are being loaded and I think it gets connected to my S3 bucket, but brings the file I want empty, so it is not getting loaded for some reason. enter image description here -
How can Django get session data in next request?
def home(request): # logged in if request.user.is_authenticated: request.session['username'] = str(request.user) request.session.set_expiry(0) # anonymous else: # how could Django get session data here ? cur = request.session.get('username', None) if cur: pass else: anon = random.choice(settings.SESSION_NAMES) request.session['username'] = anon request.session.set_expiry(42) res = render(request, 'ex/home.html', {'username': request.session['username']}) return res I'm trying to understand about session. In anonymous case above, I set session data 'username' to request that is already obtained. And in next request (after refreshing), I can get session data. But I don't understand how could it work. It's a new request, and I set 'username' in prev request, not response. How could I get 'username' from next request object despite not setting it to previous response object? -
Not able to redirect to home page using javascript after form submission in contact page
This is my contact.html page code: {% block body %} <form action="/shop/contact" method="POST">{% csrf_token %} <div class="container"> <h1 style="text-align:center;margin:10px">Contact Us</h1> <div class="mb-3"> <label for="name" class="form-label">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Enter Your Name"> </div> <div class="mb-3"> <label for="email" class="form-label">Email</label> <input type="email" class="form-control" id="email" name="email" placeholder="name@example.com"> </div> <div class="mb-3"> <label for="phone" class="form-label">Phone Number</label> <input type="tel" class="form-control" id="phone" name="phone" placeholder="Enter Your Phone Number"> </div> <div class="mb-3"> <label for="desc" class="form-label">Comments and Feedback</label> <textarea class="form-control" id="desc" name="desc" rows="3"></textarea> </div> <button type="submit" class="btn btn-primary feed">Submit</button> </div> </form> {% endblock %} And this is my javascript code in contact.html: <script> $('.feed').click(function(){ window.location.href="http://127.0.0.1:8000/shop/"; alert('Thank You for your comment or feedback. We will definately try to improve or will reach you out regarding this issue.'); }); </script> {% endblock %} This window.location.href statement is not working to redirect me to shop(or home page). I cannot change my form action to /shop because I want form data to be stored in contact page only. So what can I do?? -
Django - Page not found (404) urls.py
problem: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/home/category/coding/ Raised by: blogapp.views.BlogDetailView urls.py from django.urls.conf import path from blogapp.views import BlogDetailView, BlogListView,searchposts,CatListView from . import views app_name = "blogapp" urlpatterns = [ path('', views.BlogListView, name="blogs"), path('home/search/', views.searchposts, name= "searchposts"), path('home/category/<slug:_id>/', views.BlogDetailView, name="blog"), path('home/category/<category>/', views.CatListView.as_view(), name="category"), ] if i reverse this two path('home/category/slug:_id/', views.BlogDetailView, name="blog"), path('home/category//', views.CatListView.as_view(), name="category"), it shows the html of the category , and the path of 'path('home/category/slug:_id/', views.BlogDetailView, name="blog"),' is not showing , vice versa here is the html of navbar {% for category in category_list %} {% if forloop.counter < 4 %} <li class="nav-item"> <a class="nav-link" href="home/category/{{category.name}}">{{ category.name|title }}</a> </li> {% endif %} {% endfor %} html that i want to render {% extends "_layouts/base.html" %} {% block css %} {{block.super}} {% endblock css %} {% block page_title %}Insert_your_name_here{% endblock %} {% load static %} <!-- load the image --> {% block maincontent %} <!-- Banner --> {% block banner %} {% load static %} {% include "layout/category_banner.html" %} {% endblock %} <!-- Banner Here --> !-- This is the main template --> <section class="blog-posts grid-system"> <div class="container"> <div class="row"> <div class="col-lg-8"> <div class="all-blog-posts"> <div class="row"> {% block categories-main %} {% include "layout/category.html" %} … -
Tags imported but relationship not imported with django-import-export
I am trying to import a csv file with quotes and tags into my django-taggit custom tag model following https://docs.wagtail.io/en/stable/reference/pages/model_recipes.html#custom-tag-models. I want to keep the tags for quotes separate from tags for blog posts. After looking at previous answers How do I import tags using django-import-export? and How to import django-taggit tag in django-import-export, I managed to import the csv file. The tags are imported but the relationship is not imported (see screenshots of admin). I think the problem is in QuoteTagResource and TaggedQuoteResource but I can't figure it out. I would appreciate any help, a hint or point me to a resource I can reference? Thanks in advance! #models.py from django.contrib.auth import get_user_model from django.db import models from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TagBase, ItemBase from wagtail.snippets.models import register_snippet from ckeditor.fields import RichTextField import sys sys.path.append("..") # Adds higher directory to python modules path. from userauth.models import CustomUser @register_snippet class QuoteTag(TagBase): class Meta: verbose_name = "Quote Tag" verbose_name_plural = "Quote Tags" class TaggedQuote(ItemBase): tag = models.ForeignKey(QuoteTag, related_name="tagged_quotes", on_delete=models.CASCADE) content_object = ParentalKey(to="Quote", related_name="tagged_items", on_delete=models.CASCADE) def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted_user')[0] def set_admin(): return get_user_model().objects.get(pk=1).id class Quote(ClusterableModel): text = RichTextField(config_name='awesome_ckeditor', help_text="You must enter some … -
Django form init method failing
I have an user add form view that asks for information and saves a new user to the db. When I try saving a new user record, I get the following error. TypeError at /user/add/ __init__() missing 1 required positional argument: 'customer' Request Method: GET Request URL: http://localhost:8000/user/add/ Django Version: 3.0.5 Exception Type: TypeError Exception Value: __init__() missing 1 required positional argument: 'customer' Exception Location: D:\Job Documents\DDS\AuthenticationProject\env\lib\site-packages\django\views\generic\edit.py in get_form, line 33 Python Executable: D:\Job Documents\DDS\AuthenticationProject\env\Scripts\python.exe Python Version: 3.9.0 Python Path: ['D:\\Job Documents\\DDS\\AuthenticationProject\\auth', 'C:\\Users\\bratca\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\bratca\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\bratca\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\bratca\\AppData\\Local\\Programs\\Python\\Python39', 'D:\\Job Documents\\DDS\\AuthenticationProject\\env', 'D:\\Job Documents\\DDS\\AuthenticationProject\\env\\lib\\site-packages'] Server time: Sun, 15 Aug 2021 08:05:30 +0000 I am using customer object to differentiate users, therefore I want the form to know by whom it's being filled such that a new created user will have the same customer object as the creator. This error does not show exactly where is my bug in the code. Instead it shows some error in the actual django code, generic things that I am using. class AddUserFormView(FormView): form_class = TbUserAddForm template_name = 'users/add_user_modal.html' success_message = "Account has been created! The user is able to log in." def post(self, request): form = self.form_class(customer=request.user.customer, data=request.POST, files=request.FILES) if form.is_valid(): user_face_img_md5 = Image.open( request.FILES['user_face_img_md5'].file) user_head_img_md5 = Image.open( … -
Including two Inclusion Tags in Template Tag
Possibly the wording of my initial question is wrong, I was really unsure how to word it. Here is my current code. product_display.py from django import template from categorytree.models import CategoryTree register = template.Library() @register.inclusion_tag('templatetags/product_display.html') @register.simple_tag(takes_context=True) def this_shows_products(category, **kwargs): try: return {'ProductsModel': CategoryTree.objects.all().filter(title=category).first().products.all()} except: pass product_display.html {% load static %} <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> </style> </head> {% load product_display %} <div class='row'> {% for obj in ProductsModel %} <div class='col-xs-12 col-sm-12 col-md-6 col-lg-3 col-xl-2 col-xxl-1 ' style="margin-bottom:15px; margin-top:15px"> {% include 'products/snippets/card.html' with instance=obj cart=cart %} </div> {% endfor %} </div> Depending on the width of the screen, I want to be able to use different HTML templates. I want something like this - If screen width > 1600 then @register.inclusion_tag('templatetags/product_display.html') else @register.inclusion_tag('templatetags/product_display(1).html') end if I tried using pyauthogui, GetSystemMetrics and elsewhere in my code I have $(window).width but so far nothing I have tried has remotely solved this current problem. I could make two separate template tags but was hoping there was a more efficient way of addressing my problem. -
Django merge 2 querysets overide annotation
I have 2 models. Followers Influencers class Influencer(models.Model): username = models.CharField( _("username"), max_length=250, unique=True, null=False, blank=False, db_index=True) followers = models.ManyToManyField( "instagram_data.Follower", verbose_name=_("Followers")) I want to create a QS of followers from 2 influencers: influencer_choosen_by_user = [influ1name, influ2name] qs = Follower.objects.none() qs_influencers = Influencer.objects.filter(username__in=influencer_choosen_by_user) for influencer_obj in qs_influencers.iterator(): followers_of_influ_qs = influencer_obj.followers.all() # get all followers of this influencer followers_of_influ_qs = followers_of_influ_qs.annotate( influencer_source=Value(f'followers/{influencer_obj.username}', CharField())) qs = qs | followers_of_influ_qs ISSUE: All qs are of influencer_source == influ1name none of influ2name !!! Why ? -
AttributeError: 'QuerySet' object has no attribute 'active' in Django rest framework
I am trying to implement Coupon code feature in Django Rest framework. When a user tries to purchase a product and wants to use coupon codes presented on the item, the user should be able to get a discount based on that coupon code. The coupon should be vaild ie should be within the valid till date and also should be active. But when I try to make an order object from postman without sending the coupon codes, I got the following error. AttributeError: 'QuerySet' object has no attribute 'active' Before the application of Coupon code feature, I was able to make an order. My models: class Coupons(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE, blank=True,null=True,related_name="coupons") code = models.CharField(max_length=50,unique=True) valid_form = models.DateField() valid_till = models.DateField() active = models.BooleanField(default=False) discount = models.IntegerField(default=0) def __str__(self): return self.code Order model: Here every calculation for the prices are done. class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) order_ID = models.CharField(max_length=12, editable=False, default=id_generator) #order_items = models.ManyToManyField('OrderItem',blank=True, null=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) ordered = models.BooleanField(default=False) current_points = models.FloatField(default=0) total_price = models.FloatField(blank=True,null=True) point_spent = models.FloatField(default=0) coupon_code = models.CharField(max_length=15, blank=True, null=True) def final_price(self): total = sum([_.price_1 for _ in self.order_items.all()]) total -= Decimal(self.price_of_points) dis = self.price_of_coupon print(dis) total = total - … -
how to search or filter data of two different model and return it in one
I have two models. First model is about the main information and the Second one is the detail of the first model(actually its about the way that the first one is delivered) and the second model has the ForeignKey of the first one and each data of the first model can have many data in the second one. what I want to do is to filter the data of both models and return it in one row of table! My First Model : class Report(models.Model): factory_account = models.ForeignKey(Account, on_delete=models.CASCADE) factory_state = models.CharField(choices=State, max_length=20) factory_id = models.IntegerField() factory_name = models.CharField(max_length=50) buyer_state = models.CharField(choices=State, max_length=20) buyer_name = models.CharField(max_length=50) buyer_national_id = models.IntegerField() buyer_city = models.CharField(max_length=50) buyer_address = models.CharField(max_length=500) landline_buyer_phone = models.IntegerField() buyer_phone = models.IntegerField() date = jmodels.jDateField() invoice_number = models.IntegerField(unique=True) bran_number = models.IntegerField() price = models.IntegerField() delivered = models.IntegerField() delivery_balance = models.IntegerField() My Second Model : class DeliverDetail(models.Model): invoice_number = models.ForeignKey(Report, on_delete=models.CASCADE, null=True) date = jmodels.jDateField() delivered = models.IntegerField() car_type = models.CharField(max_length=20) car_tag = models.CharField(max_length=20) driver_name = models.CharField(max_length=50) driver_national_code = models.IntegerField() My Filter.py (Using Django-filter(https://pypi.org/project/django-filter/)): class myFilter(django_filters.FilterSet): car_type = django_filters.CharFilter(lookup_expr='icontains', distinct=True, field_name='deliverdetail__car_type') car_tag = django_filters.CharFilter(lookup_expr='icontains', distinct=True, field_name='deliverdetail__car_tag') driver_name = django_filters.CharFilter(lookup_expr='icontains', distinct=True, field_name='deliverdetail__driver_name') driver_national_code = django_filters.NumberFilter(lookup_expr='iexact', distinct=True, field_name='deliverdetail__driver_national_code') class Meta: model = Report fields … -
Django: how to show a narrowed drop-down list based on the previous selection?
For example I would like make an instance CAR with two information: Manufaturer and CarModel. class Manufacturer(models.Model): name = models.CharField(max_length=10, blank=False) class CarModel(models.Model): name = models.CharField(max_length=10, blank=False) class Car(models.Model): producer = models.OneToOneField(Manufacturer, on_delete=models.CASCADE()) carmodel = models.OneToOneField(CarModel, on_delete= models.CASCADE()) Of course before I would make an instance for class Car I would have to make instances for class Manufacturer and CarModel. I would make BMW, Volvo, Toyota for Manucaturer and then series 3, series 5, X5, X7, XC90, V40, Prius, Land Cruiser, Corolla. Finally when I would make an instance for class Car I would see first: BMW, Volvo, Toyota I would choose Toyota and then I would like see in next drop-down list only: Prius, Land Cruiser, Corolla Of course BMW does not manufature Prius :) How can I do something like filter for that? -
What mistake am I making to cause these Django E304 errors?
I cannot for the life of me figure out what I'm doing wrong here, any help would be very much appreciated! The Goal: We have admins and appraisers signing up on the site. Admins can of course do everything you'd expect from the /admin site and appraisers have their own site, /portal. What I'm trying to do now is improve my current model so that I can add more fields to the appraiser users. The admin user's fields are a subset of the appraiser user's fields. The Error: SystemCheckError: System check identified some issues: ERRORS: accounts.Appraiser.groups: (fields.E304) Reverse accessor for 'accounts.Appraiser.groups' clashes with reverse accessor for 'accounts.Admin.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.Appraiser.groups' or 'accounts.Admin.groups'. accounts.Appraiser.user_permissions: (fields.E304) Reverse accessor for 'accounts.Appraiser.user_permissions' clashes with reverse accessor for 'accounts.Admin.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.Appraiser.user_permissions' or 'accounts.Admin.user_permissions'. accounts.Admin.groups: (fields.E304) Reverse accessor for 'accounts.Admin.groups' clashes with reverse accessor for 'accounts.Appraiser.groups'. HINT: Add or change a related_name argument to the definition for 'accounts.Admin.groups' or 'accounts.Appraiser.groups'. accounts.Admin.user_permissions: (fields.E304) Reverse accessor for 'accounts.Admin.user_permissions' clashes with reverse accessor for 'accounts.Appraiser.user_permissions'. HINT: Add or change a related_name argument to the definition for 'accounts.Admin.user_permissions' or 'accounts.Appraiser.user_permissions'. Before … -
How to access list of dictionary in Django template
I am very new to Django and implemented a post-api call by watching couple of tutorials and one of the fields gets a list of dictionaries, want to access the key value pair in Django template, instead it is taking char by char, how to solve this problem? models.py class Leads(models.Model): Name = models.CharField(max_length=50) Mobile = models.CharField(max_length=13) Email = models.CharField(max_length=50) Message = models.CharField(max_length=300) created_on = models.DateTimeField(default=datetime.now()) modified_on = models.DateTimeField(default=datetime.now()) Example input for above api call will be: Name = rakesh Mobile = 1234567890 Email = email@mail.com Message = [{'key': 'some text', 'value': 'some value'}, {'key': 'some text', 'value': 'some value'}] template.html {%for user in users %} <tr> <td>{{user.Name}}</td> <td>{{user.Mobile}}</td> <td>{{user.Email}}</td> <td>{{user.Message}}</td> </tr> {%endfor%} If I try like above then the output is rakesh 1234567890 emaik@mail.com [{'key': 'some text', 'value': 'some value'}, {'key': 'some text', 'value': 'some value'}] If I add another loop for Message field then the Message field is not showing any output: {%for user in users %} <tr> <td>{{user.Name}}</td> <td>{{user.Mobile}}</td> <td>{{user.Email}}</td> {%for i in user.Message %} <td>{{i.key}}</td> <td>{{i.value}}</td> {%endfor%} </tr> {%endfor%} Output: displaying string by string rakesh 1234567890 emaik@mail.com If I try like this then: {%for user in users %} <tr> <td>{{user.Name}}</td> <td>{{user.Mobile}}</td> <td>{{user.Email}}</td> {%for i in user.Message … -
Template tags not working inside an included template
I include tags inside an included template. However, even though I extend the base template, in my templates (list.html) the tags are not rendered. Perhaps something I am missing? base.html: <div class="content-page"> <div class="content"> <div class="container-fluid"> {% include 'partials/pageTitle.html' %} </div> </div> </div> partials/pageTitle.html: <h4 class="page-title">{% block pageTitle %}{% endblock pageTitle %}</h4> list.html (tags not working) {% extends 'base.html' %} {% block pageTitle %} Basic Tables {% endblock pageTitle %} -
django IntegrityError for create object
I have this models . When i use One To One relation ship for real_estate field in Profile model and create new object i get this error => IntegrityError at /admin/users/profile/add/ NOT NULL constraint failed: users_profile.real_estate_id class Business(models.Model): name = models.CharField(max_length=200) image = models.ImageField() homes = models.ManyToManyField(Homes , related_name='home', blank=True) create = models.DateField(auto_now_add=True) number = models.IntegerField() class Profile(models.Model): CHOICES = ( ('RE', 'مشاور املاک'), ('S', 'فروشنده'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) real_estate = models.OneToOneField(Business , related_name='business' ,on_delete=models.CASCADE, blank=True) image = models.ImageField(blank=True) type_of_user = models.CharField(max_length=300, choices=CHOICES) phone_number = PhoneNumberField(unique = True, null = False, blank = False) -
Insert a python dictionary into postgres jsonb field
I'm looking to a postgresql query or function to replace the flowing python code def insert_data(pk, data) json_str = Employee.objects.filter(pk=pk).values_list('time_log', flat=True)[0] dt = data["date"] data.pop("date") if json_str.get(f"{dt}") == None: json_str[f"{dt}"] = [data] else: json_str[f"{dt}"].append(data) # time_log is a `jsonb field` Employee.objects.filter(pk=pk).update(time_log=json_str) The code works but not efficient and causes bottlenecks. Data is dictionary containing a date and two datetime objects like this: data = { '2021-08-13': [ { 'clock_in': '2021-08-15T04:16:41.307Z', 'clock_out': '2021-08-14T21:16:44.491-07:00' } ] } IF the key does not exist, make a new key value pair, the key is the date in data and value is a list containing the data dictionary. IF the key exists, append data into key of date from data dictionary. -
what are the various ways for Styling the Django Forms?
was working with Django forms, and to beautify the Django forms I came across widgets, and after learning it got to know that we can customize widgets in two ways: it can be via widget instance or via widget class. Later came across django-crispy; django-bootstrap. Which will do the same beautification of the forms along with various other advantages over other. But was wondering, how many more such library / packages / apps are there, and is there any short of description for each, which might help me and others too. Thanks -
Crontab ModuleNotFoundError
I have prepared a py Script to update my Django database and upload a file to gdrive once a day. Trying to use Crontab along with python to run the py script. ModuleNotFoundError: No module named 'googleapiclient' I have already installed googleapiclient module. There is no error while running the same script in venv (virtual environment). 0 2 * * * /usr/bin/python3 /home/user/folder1/folder11/script2.py How to access the already installed module inside crontab..? -
change table header and content dynamically in JavaScript
I have a web app, frontend using normal HTML, backend using Django. In the HTML page, there's a table, which load data by calling API. I want to change table header dynamically in JavaScript after the if condition(in my case:if params['Add_Information'] == "eText_iBookStore":), so the table could have different header based on user selection. How could I change the header and content of my table in Javascript? <table contenteditable='true' class="table table-bordered table-sm" width="100%" cellspacing="0" style="font-size: 1.0rem;" id="bk-table" data-toggle="table" data-toolbar="#toolbar" data-cookie="true" data-cookie-id-table="materialId" data-show-columns="true" data-show-refresh="true" data-show-fullscreen="true" data-show-export="true" data-height="650" data-click-to-select="true" data-id-field="id" data-show-footer="true" data-url="/api/materials/" data-query-params="queryParams" data-remember-order="true" data-pagination="true" data-side-pagination="server" data-total-field="count" data-data-field="results"> <thead class="thead-dark"> <tr contenteditable='true'> <th data-field="id" data-sortable="true">ID</th> {# <th data-field="courseId" data-visible="false"></th>#} <th data-field="courseCode" data-sortable="true" data-formatter="renderCourse">Course Code</th> <th data-field="book.title" data-sortable="true" data-formatter="renderTitle">Course Material Title</th> <th data-field="book.isbn" data-sortable="true">ISBN</th> <th data-field="book.publisher" data-sortable="true">Publisher</th> <th data-field="retail_price_display" data-sortable="true">Retail Price</th> <th data-field="semester_course.school" data-sortable="true">School</th> <th data-field="year" data-sortable="true">Year</th> <th data-field="month" data-sortable="true">Semester</th> <th data-field="quota" data-sortable="true">Course Quota</th> </tr> </thead> </table> <script> {% block script %} var $table = $('#bk-table'); var $ok = $('#ok'); $(function () { $ok.click(function () { $table.bootstrapTable('refresh') }); function queryParams(params) { params['limit'] = localStorage['Format']; params['discipline'] = localStorage['discipline']; params['Add_Information'] = localStorage['Add_Information']; if params['Add_Information'] == "eText_iBookStore": ***//Here should be header changing part*** params['publisher'] = $("[name='publisher']").val(); params['code'] = $("[name='code']").val(); console.log(params); return params; } {% endblock %} … -
Django - How to simplify the create new row of a table with many foreign key?
Here is the sample model: class GenderDecode(models.Model): gender_code = models.IntegerField(primary_key= True) gender_explain = models.CharField(max_length=100) class AgeDecode(models.Model): age_code = models.IntegerField(primary_key= True) age_explain = models.CharField(max_length=100) class User(models.Model): name = models.CharField(max_length=100) age_group = models.ForeignKey(AgeDecode, on_delete = models.CASCADE) gender_group = models.ForeignKey(GenderDecode, on_delete = models.CASCADE) The initial setup of two tables GenderDecode and AgeDecode: GenderDecode gender_code gender_explain 1 male 2 female AgeDecode age_code age_explain 1 young 2 old Provided I want to create a new user - John Male Young. I have to do this. User(name = 'John', age_group = AgeDecode.objects.filter(gender_code=1).first(), gender_group = GenderDecode.objects.filter(age_code=1).first() ).save() I want to do this User(name = 'John', age_group = 1, gender_group = 1 ).save() But I got this error ValueError: Cannot assign "1": "User.gender_group" must be a "GenderDecode" instance. Well, if the above syntax is a must, is there any way to go around to simplify my new row code ? -
How do I get User's updated name from Python Firebase Admin SDK?
I am using FirebaseAuth on Flutter, and send IdToken to my Django backend to use firebase_admin.auth.verify_id_token(id_token) to verify the user and get the user's basic info. But the user's info doesn't show the latest profile. I changed my Google account user name, but the name decoded from IdToken still showing the old name even though I signed out and signed in again on frontend. How do I get the latest user's profile? Thanks -
Django 404 Error: path doesn't go down urls.py
So I'm trying to make an index.html for the homepage of my Django project. I made an app called pages. Note that the templates folder is empty (moving index.html to templates did nothing). admin.py and models.py also contain nothing. I configured my TEMPLATES settings as such: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] In my root project folder, urls.py looks like this. from django.contrib import admin from django.urls import path from django.conf.urls import include # from pages.views import home_view urlpatterns = [ path('homepage/', include('pages.urls')), path('admin/', admin.site.urls), path('explorer/', include('explorer.urls')), ] In the views.py file of the pages app: from typing import ContextManager from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): # Render the HTML template index.html return render(request, 'index.html', context=ContextManager) In the pages app (not project root folder), urls.py looks like this (I created this file myself): from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] And index.html: <!DOCTYPE html> <title>Test</title> <p>Test</p> Here is the full file structure. Here is what happens when I run the server: Where http://127.0.0.1:8000/ is … -
how to set up docker compose to use ssh to connect to AWS RDS on private subnets via EC2 Bastion
I have the following configuration of a django app that ssh'ed into an ec2 bastion and i tried to follow this example https://emmer.dev/blog/tunneling-a-database-connection-with-docker-compose/ I am still not able to configure my docker compose file to accept ssh tunnel to AWS Postgres RDS which reside in a private subnets. version: "3.9" services: app: build: ./app restart: always env_file: .env volumes: - ./app:/app - ./app/static:/app/static ports: - 8000:8000 depends_on: - db links: - db:db networks: - "app_network" db: image: postgres restart: always env_file: .env volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - "app_network" networks: app_network: driver: bridge volumes: postgres_data: What happen is that using django itself via python manage.py runserver i am able to connect to the RDS instance and everything is fine. Now when i try to do the same with docker compose, docker compose exec app python manage.py migrate or try to access RDS from django shell inside the docker compose after it started with docker-compose up -d , the database crash with the message below: django.db.utils.OperationalError: could not translate host name "xxx.zzz.us-east-z.rds.amazonaws.com" to address: nodename nor servname provided, or not known clearly the issue is that docker compose is not picking the ssh tunnel connection i have tried multiple … -
Django & Js question slider with a next button appear on last question
i have a questions slider made with JS with a next button to go to next questions, i want to disable that button in last slide which is the submit slide. I have tried to remove the id from last slide but it wont appear in the sliders any help or advices to improve the code will be great Here is my code: HTML: W <div class="slider"> <form class="form" action="" method="post"> <!-- fade css --> {% csrf_token %} {% for question in questions %} <div class="myslide fade"> <div class="txt"> <p>{{question.question}}</p> <input id="{{question.id}}" type='radio' name="{{question.id}}" value="{{question.category}}"> <label for="{{question.id}}">Yes</label> <br> <input id="{{question.id}}1" type='radio' name="{{question.id}}" value="no"> <label for="{{question.id}}1">No</label> <br> </div> <img src="{{question.img.url}}" style="width: 100%; height: 100%;"> </div> {% endfor %} <div class="myslide fade"> <div class="txt"> <p>You finished all questions</p> <input type="submit" class="btn" value="Submit"> </div> <img src="{% static 'img/img4.jpg'%}" style="width: 100%; height: 100%;"> </div> <a class="next" onclick="plusSlides(1)">Next</a> </form> </div> JS: const myslide = document.querySelectorAll('.myslide'), dot = document.querySelectorAll('.dot'); let counter = 1; slidefun(counter); let timer = setInterval(autoSlide, 8000); function plusSlides(n) { counter += n; slidefun(counter); resetTimer(); } function currentSlide(n) { counter = n; slidefun(counter); resetTimer(); } function resetTimer() { clearInterval(timer); timer = setInterval(autoSlide, 8000); } function slidefun(n) { let i; for(i = 0;i<myslide.length;i++){ myslide[i].style.display = …