Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I delete all user data when deleting profile on Django using signals.py
how can I delete all user data when deleting a user profile on Django using signals.py? I am trying to delete a custom user model using Django and when the profile is deleted I want to delete all data of that user using signals.py how can I create it? @receiver(post_delete, sender=models.Profile_user) def delete_auth_user_model_handler(sender, instance, *args, **kwargs): user_instance = instance.user user_instance.delete() I want to delete blogs of the user-written when the profile is deleted -
DRF - How to using serializer to load related data
I have a self related table Employee, and Project table has foreignkey to related to Employee table. class Employee(models.Model): eid = models.CharField(primary_key=True, max_length=10) name = models.CharField(max_length=10) pmid = models.ForeignKey('self', models.RESTRICT, related_name='team_member', blank=True, null=True,) class Project(models.Model): pid = models.CharField(primary_key=True, max_length=10) description = models.CharField(max_length=100) teamleaderid = models.ForeignKey(Employee, models.RESTRICT) and serializers.py class SubEmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = '__all__' class EmployeeSerializer(serializers.ModelSerializer): team_member = SubEmployeeSerializer(many=True, read_only=True) class Meta: model = Employee fields = '__all__' class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = '__all__' depth = 1 views.py class ProjectList(generics.ListAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer I hope when request ProjectListView I can get teamleaderid with team_member data but I don't know why team_member not show in my response. [ { "pid": "p1", "description": "p1 project", "teamleaderid": { "eid": "1", "name": "n1", "pmid": null, ###### how to show below data ### # "team_member": [ # # { # # "eid": "5", # # "name": "n5", # # "pmid": "1" # #} # ################################# } } ] -
How to remove or disable unwanted languages in Django 4.1.1
I had a question about translations in Django... So I have a project with 4 languages defined in my settings.py LANGUAGES = [ ('en', _('English')), ('fr', _('French')), ('de', _('German')), ('it', _('Italy')), ] now I want to disable all languages except english, so I've been searching in google how to do it, and find this post on SO => enter link description here, than I tried to comment all languages except english, after that I've done ./manage.py makemigrations => ./manage.py migrate migrations went without any error, BUT in my language list they didn't dissapear... also I've been find code that as I think forms this list... I changed thare hardcoded langlist from language_list = ['en', 'it', 'de', 'fr'] to language_list = settings.LANGUAGES and also nothing happened with my UI language list choices... So, question: how properly I can disable unwanted languages in my Django application; P.S I'm new in python and Django at all, so please can anyone help me with this? -
400 bad request in "POST" request in django react
i have react component in were im posting data in djnago back end. but it always gives me 400 bad request as response and in backend console too. here is my code. ` import axios from 'axios' import React, { useEffect, useState } from 'react' import { Button } from 'react-bootstrap' import API_URL from './BackendDefaustUrls'; import {useNavigate, useParams} from "react-router-dom" const AddProduct = () => { const [Image , setImage] = useState(null) const [Name , setName] = useState("") const [Price , setPrice] = useState("") const [Description , setDescription] = useState("") const [Category , setCategory] = useState("") const navigate = useNavigate() const {id} = useParams() const getProduct = async () => { await axios.get(API_URL+`api/${id}/`).then(response => { return response.data }).then(data => { setName(data.name) setImage(data.image) setPrice(data.price) setDescription(data.description) setCategory(data.category) }) } useEffect(()=>{ getProduct() },[]) const AddProductInfo = async () =>{ let formField = new FormData() formField.append('name',Name) formField.append('price',Price) formField.append('description',Description) formField.append('category',Category) if (Image != null) { formField.append('image',Image) } await axios({ method: 'POST', url: API_URL + `api/`, data:formField }).then(response => { console.log(response.data); navigate("/") }) } return ( <div> <div className='container'> <div className="w-75 mx-auto shadow p-5"> <h2 className="text-center mb-4">Add A Student</h2> <div className='form-group'> {/* image */} <label>Select Image To Upload</label> <input type="file" name="image" className='form-control form-control-lg' onChange={e=>setImage(e.target.files[0])} /> </div> … -
How to add message box to admin panel
I have added my custom action that performs sending message to users. But I don't know how can I put my message where. So how can I add message field to my admin panel and connect to my custom action button? -
Django; Can't Access to Other Models inlineformset_factory Fields
I have a successfully working inlineformset_factory form. I create this model with a button and inherit the data in it from another model. However, I was not able to access the inlineformset_factory fields in the other model. def create_offer_button(request): if request.method == "POST": post = request.POST.get("post_pk") obj = RequestModel.objects.get(pk=post) if obj.is_accepted: OfferModel.objects.create(request_model_name=obj, request_title=obj.request_title, delivery_time=obj.delivery_time, shipping_country=obj.shipping_country, shipping_address=obj.shipping_address, preferred_currency=obj.preferred_currency, shipping_term=obj.shipping_term, delivery_term=obj.delivery_term) obj.is_offer_created = True obj.save() return redirect(request.META.get("HTTP_REFERER")) How can i access to RequestModel's inlineformset_factory fields? I tried many methods but I could not reach the formset fields of the inheritance model. -
Django: Object is not saved to DB when submitting form with CreateView
I have a CreateView to create artists but when submitting the form, nothing happens. models.py class Artist(models.Model): name = models.CharField(max_length=222, unique=True) slug = models.SlugField(unique=True, null=True) age = models.PositiveIntegerField(null=True,blank=True) location = models.CharField(max_length=222, null=True, blank=True) bio = models.TextField(null=True,blank=True) booking_fee_per_hour = models.PositiveIntegerField(verbose_name="Booking Fee per hour") def __str__(self): return self.name views.py class ArtistsAddView(views.CreateView): template_name = 'add_artist.html' model = Artist fields = '__all__' success_url = '/' templates -> add-artist.html <form method="post" action="{% url 'artist add' %}"> <p>{{ form.name.label_tag }} {{ form.name }}</p> <p>{{ form.age.label_tag }} {{ form.age }}</p> <p>{{ form.location.label_tag }} {{ form.location }}</p> <p>{{ form.bio.label_tag }} {{ form.bio }}</p> <input type="hidden" name="next" value="{{ next }}"> <button>Submit</button> {% csrf_token %} </form> I intentionally hid 2 of the fields: slug and booking_fee_per_hour. I would like to make them available only for admins. If I write: <form method="post" action="{% url 'artist add' %}"> {{ form.as_p }} <input type="hidden" name="next" value="{{ next }}"> <button>Submit</button> {% csrf_token %} </form> then the artist is saved to the DB but also the normal user can see slug and booking_fee_per_hour. Could you please help me? -
TinyMCE referer header missing in Django
I am using TinyMCE to write text with markup in my Django project. Im am displaying the TinyMCE editor on a user page where they can type text with markup. This works just fine. However: The editor prompts the following message when displaying the page: We’re unable to check your domain because the referer header is missing. Please read the Guide on how to ensure your referer header is present, so we can then customize your editor experience. I can't seem to figure out what is missing and how to fix it. Any help would be much appreciated! In my models I implement the TinyMCE as follows: bottle_info = HTMLField() -
How to Override CreateModelMixin corrctly
I want to override CreateModelMixin with my own class which derived from ModelViewSet this is the class i want to override class CreateModelMixin: """ Create a model instance. """ def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): try: return {'Location': str(data[api_settings.URL_FIELD_NAME])} except (TypeError, KeyError): return {} in the first instinct, I want to override only the create function with a different serializer but would it be more correct to override perform_create? if someone can guide me how it is the most correct way to override that will be much of help thank you -
How can i pass validated data to another custom validator class in DRF?
I Have this kind of serializer.py class PostSerializer(serializers.ModelSerializer): title = serializers.CharField(validators=[TitleValidator()]) slug = serializers.CharField(validators=[SlugsValidator()], max_length=100, required=False) and i have two class validators for this fields class TitleValidator: MIN_TITLE_LENGTH = 20 def __call__(self, title: str): if len(title) < self.MIN_TITLE_LENGTH: raise ValidationError(f"Min title length is {self.MIN_TITLE_LENGTH}") return title class SlugsValidator: def __call__(self, slug): # Get title here return slug How can I pass the validated title into SlugValidator class? I've tried to pass data directly to the TitleValidator instance, but the only thing I can get is the field itself, not an actual value. Another way was to pass data inside validate() method, but seems like custom class validators are executed first, and i' getting an error that the title argument is not provided. Is there any way I can achieve this? -
Bootstrap 5.0 Navbar Dropdown not working
I couldn't make the dropdown on my navbar work. When I click on it nothing happens. What might be the problem? I checked similar posts but couldn't find a solution. Am I missing a script or something? layout.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <body> <nav class="navbar" style="background-color: #e6e2c2;"> <div class="container-fluid"> <a class="navbar-brand" href="#"> <img src="{% static 'potbs/potbs.png' %}" alt="Logo" width="50" height="30" class="d-inline-block align-text-top"> Pat on the Back Studios. </a> <div class="navbar-expand" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> {% if user.is_authenticated %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-bs-toggle="dropdown" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Profile </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Profile</a></li> <li><a class="dropdown-item" href="#">Earned Badges</a></li> <li><hr class="dropdown-divider"></li> <li><a class="nav-link" href="{% url 'logout' %}">Log Out</a></li> </ul> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Register</a> </li> {% endif %} </ul> </div> </div> </nav> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz9ATKxIep9tiCxS/Z9fNfEXiDAYTujMAeBAsjFuCZSmKbSSUnQlmh/jp3" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js" integrity="sha384-cuYeSxntonz0PPNlHhBs68uyIAVpIIOZZ5JqeqvYYIcEL727kskC66kF92t6Xl2V" crossorigin="anonymous"></script> </body> </html> -
How to send JWT REFRESH TOKEN as http only cookie in django?
I am using Django(REST FrameWork, SimpleJWT) and React for my project. For autentication I am using JWT method. According to some articles, storing and sending REFRESH TOKEN in HttpOnly Cookie is the a best and secure way. Since I am learning WebDevelopment I can't able to find any source to about it. This is my views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer def post(self, request, *args, **kwargs): try: response = super().post(request) except InvalidToken: return Response({'Invalid or expired token'}) refresh_token = RefreshToken.for_user(request.user) response.set_cookie('refresh_token', refresh_token, httponly=True) return response class RegisterView(generics.CreateAPIView): queryset = User.objects.all() permission_classes = (AllowAny,) serializer_class = RegisterSerializer class LogoutView(generics.CreateAPIView): def post(self, request): refresh_token = request.data['refresh_token'] token = RefreshToken(refresh_token) token.blacklist() return Response({'Logout':'Successfullly'}) as you can i even tried to over write the post method in MyTokenObtainPairView. This is my urls.py path('api/login/', MyTokenObtainPairView.as_view(), name="token_obtain_pair"), path('api/token/refresh/', TokenRefreshView.as_view(), name="token_refresh"), path('api/register/', RegisterView.as_view(), name="auth_register"), path('api/logout/', LogoutView.as_view(), name="logout"), This is my settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(hours=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=2), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(hours=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=2), } I am expecting a way to … -
API to get all pincodes inside a radius
I'm working on a python application where we need to get all the pincodes within a specific radius. We have a base location and a radius of 10Km is drawn from this base pincode. Do we have any API where this can be achieved? FYA - Mainly looking for Indian PostalCodes. -
How to customize django loginview
path('account/login', auth_views.LoginView.as_view(template_name='main/log_form.html'), name='login'), path('account/logout/', auth_views.LogoutView.as_view(template_name='main/logout.html'), name='logout'), How to customize django loginView? -
Django comment not saving to post
Comments are saving to DB but not linking to Post, unless I manually go to Admin page and link. MODELS.PY class Post(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=50) info = models.TextField(max_length=2000) slug = models.SlugField(null=True, unique=True, max_length=300) created = models.DateField(null=True, auto_now_add=True) approved = models.BooleanField(default=False, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE, null=True) name = models.CharField(max_length=50, verbose_name="Name") comment = models.TextField(max_length=500, verbose_name="Review") created = models.DateField(null=True, auto_now_add=True) approved = models.BooleanField(default=False, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) FORMS.PY class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['name','comment'] VIEWS.PY def create_comment(request, slug): form = CommentForm() post = Post.objects.get(slug=slug) if request.method == "POST": form = CommentForm(request.POST) comment = form.save() review.post = post review.save() messages.success(request, 'Your comment was successfully submitted!') return render(request, 'post.html', {'post': post, 'form':form}) return render(request, 'post.html', {'post': post, 'form':form}) From Admin page I can add comment and manually link to post, but from frontend form, comment is created and saved to DB but not linked to any post -
django rest framework Convert a view to api
I am a beginner in drf and I need to create this view in drf, but I don't know what method I should use. class CategoryList(ListView): template_name = "blog/categorylist.html" paginate_by = 10 def get_queryset(self): global my_category slug = self.kwargs.get('slug') my_category = get_object_or_404(Category, slug=slug) return my_category.articles.published() def get_context_data(self, **kwargs): context = super(CategoryList, self).get_context_data(**kwargs) context['category'] = my_category return context -
How to write test for Django image url
I'm writing my first test as a Django developer. How do I write a test for the image property of this model shown below class Project(models.Model): engineer = models.ForeignKey(Engineer, on_delete=models.CASCADE) name = models.CharField(max_length=100) tech_used = models.CharField(max_length=200) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) image = models.ImageField(default="project.png") description = models.TextField(null=True, blank=True) repo_url = models.URLField(null=True, blank=True) live_url = models.URLField(null=True, blank=True) make_public = models.BooleanField(default=False) def __str__(self): return self.name @property def image_url(self): try: url = self.image.url except: url = "" return url class Meta: ordering = ["-created"] I have tried to conjure some patches from here and there although I don't fully understand what my test.py code I just thought to include it to my question to show my efforts class TestModels(TestCase): def setUp(self): new_image = BytesIO() self.image = Project.objects.create( image=ImageFile(new_image) ) def test_image_url(self): self.assertEquals(self.image.image_url, '') Please a help on the above question and an explanation of whatever code given as help will be highly appreciated. -
How to process two GET requests, at the same time and collect the data in javascript
Hello I have a question and a doubt, I am in a view, when I give a button I do the following code function pagar_recibo(id) { $.ajax ({ delay: 250, type: 'GET', url: '/general/recibo/add', data: { 'id': id, 'action_al': 'add_alumnos', }, }); }; This button is a href that goes to another url, that is to say it makes another request to the server with GET then in the new view in the get_context_data I have the following def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['arg'] = json.dumps(self.alum()) # context['arg'] = self.alum() return context and the function is as follows def alum(self, **kwargs): data = [] try: action = self.request.GET.get('action_al', False) print(action) if action == False: return elif action == 'add_alumnos': data = [] id = int(self.request.GET['id']) Alumnos = Alumno.objects.filter(pk=id) for i in Alumnos: item = i.toJSON() item['text'] = i.get_full_name() data.append(item) print(data) except Exception as e: data['error'] = str(e) return data This is how I pick it up in the template window.data = {{ arg|safe }}; The problem is that one GET request is empty, the url change and the other is the ajax request with the given key and value, but I always get empty windows data, how could I … -
How to paginate comments for detail_view?
I'm writing a simple blog and I need paginate comments for each posts but I don't know how to do it. Thanks for help! There is my models: class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) short_description = models.CharField(max_length=230, default='Post') text = models.TextField() is_published = models.BooleanField(default=False) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) username = models.CharField(max_length=35) comment = models.CharField(max_length=120) is_published = models.BooleanField(default=False) def __str__(self): return self.comment There is my views: class PostDetail(generic.DetailView): template_name = 'user/post.html' model = Post def comment_view(request, pk): form = CommentCreateForm() if request.method == 'POST': form = CommentCreateForm(request.POST) if form.is_valid(): username = request.user comment = form.cleaned_data['comment'] Comment.objects.create(username=username, comment=comment, post_id=pk) return redirect('PostDetail', pk) return render(request, 'user/comment_view.html', {'form': form}) And there is my template: { object.title }} {% if object.author.id %} <a href="{% url 'public_profile' object.author.id %}">{{ object.author }}</a> {% endif %} <p>{{ object.text }}</p> <h4>Comments</h4> {% for comment in object.comment_set.all %} {{ comment.username }} <p>{{ comment }}</p> {% endfor %} <p><a href="{% url 'comment_view' object.id %}">Leave comment</a></p> Is it real to paginate comments? How I should paginate comments in detail_view? -
when I showdown my laptop it's ok. but now my code give me error
Hello I by Django writing a blog and I get this error can you help me? It's my view: class CategoryList(ListView): paginate_by = 3 template_name = "blog/category_list.html" def get_queryset(self): global category slug = self.kwargs.get("self") category = Category.objects.active().filter(slug= slug) return category.articles.published() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["category"] = category return context it's my model and model manager: class CategoryManager(models.Manager): def active(self): return self.filter(status= True) class Category(models.Model): parent = models.ForeignKey('self' , default=None , null=True , blank=True , on_delete= models.SET_NULL , related_name='children' , verbose_name="زیر دسته" ) title = models.CharField(max_length = 200 , verbose_name = "عنوان دسته بندی") slug = models.SlugField(max_length = 100 , unique = True , verbose_name = "آدرس دسته بندی") status = models.BooleanField(default = True , verbose_name = "آیا نمایش داده شود؟") position = models.IntegerField(verbose_name = "پوزیشن") class Meta: verbose_name = 'دسته بندی' verbose_name_plural = 'دسته بندی ها' ordering = ["parent__id","-position"] def __str__(self): return self.title objects = CategoryManager() I check everything but it doesn't fix -
Style django form without bootstrap
im currently new to django. I have search for many tutorial how to style django form without using any bootstrap. Can i style django form without bootstrap and using pure 100% css?. If it can be please show some example I dont want use bootstrap with django form because it limited for me to style it. So i want to know the method to style django form with no bootstrap -
How to list all objs and retrieve single obj using django drf generic views
I am trying to create a single class based view for retirving, listing, and creating all of my orders. I have gotten create and retirve to work but listing is giving some problems. I am using DRF generic views to extend my view and have added the generics.ListApiView to my class. Once I added this however my retirve route started acting unusal. It is returning to me a list of all the orders when I just want a speific one. I tried to just add the generics.ListApiView to my class and override the list and get_queryset functions but that just started to affect my retrive view. class Order(generics.ListAPIView, generics.CreateAPIView, generics.RetrieveAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = addOrderSerializer def get_queryset(self, **kwargs): user = self.request.user return Order.objects.filter(user=user) def get_object(self): pk = self.kwargs['pk'] obj = Order.objects.get(pk=pk) return obj def get_item_serializer(self, *args, **kwargs): return addItemSerializer(*args, **kwargs) def get_shipping_serializer(self, *args, **kwargs): return addShippingSerializer(*args, **kwargs) def create(self, request, *args, **kwargs): user = request.user data = request.data orderItems = data.get('orderItems') print(data) if not bool(orderItems): return Response('No Order Items', status=status.HTTP_400_BAD_REQUEST) else: # TODO - Create Order orderSerializer = self.get_serializer(data=data) orderSerializer.is_valid(raise_exception=True) order = orderSerializer.save(user=user) # TODO - Create Shipping Address shippingSerializer = self.get_shipping_serializer(data=data) shippingSerializer.is_valid(raise_exception=True) shippingSerializer.save(order=order) # TODO - Create Order … -
Django AWS Elastic Beanstalk: Web services not running
I have a Django project that I got up and running on an EC2 instance via Elastic Beanstalk. I have been attempting to connect my site to MySQL on RDS and have been running into problem after problem. I started by following AWS's docs, but very quickly had issues that were resolved by adding an 01_packages.config file under .ebextensions per some other questions on here. Currently my environment is "Degraded" and I honestly can't figure out why... My settings.py has correct DATABASE information, the ALLOWED_HOSTS is correct. When I go to "Causes" for the degradation it tells me: Following services are not running: web. Here are some of the last 100 lines of the logs right after I tried to deploy my project once again. What is causing the issue? /var/log/nginx/error.log 2022/12/10 03:44:52 [error] 27428#27428: *15 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.0.56, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "assignment-env.eba-gx7qabzc.us-west-2.elasticbeanstalk.com" 2022/12/10 03:44:52 [error] 27428#27428: *15 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.0.56, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "assignment-env.eba-gx7qabzc.us-west-2.elasticbeanstalk.com", referrer: "http://assignment-env.eba-gx7qabzc.us-west-2.elasticbeanstalk.com/" 2022/12/10 03:44:53 [error] 27428#27428: *15 connect() failed (111: Connection refused) while connecting to upstream, client: … -
Djano template: Could not parse the remainder: '[]' from '[]'
I'm trying to do something like this to create a new list and append elements to it within a block of template code. {% with my_list=[] %} {% for item in items %} {{ item }} {% with my_list=my_list|add:item %} {# my_list now contains the current item #} {% endwith %} {% endfor %} {% endwith %} But Django says Could not parse the remainder: '[]' from '[]' -
TypeError at /check 'ModelBase' object is not iterable in django
I am trying to print data from database in command prompt(terminal) when i run program it gives error showing TypeError at /check 'ModelBase' object is not iterable i dont understand what the proble is please help me to solve it. this is my views.py here the table name is dish and i want to print name of that dish ` def check(request): dishs = dish.objects.all() for dishs in dish: print(dishs.dish_name) params = {'dish': dishs} return render(request, "card/check.html", params) this is my urls.py urlpatterns = [ path('index', views.index, name="index"), path('check', views.check, name="check"), path('delete/<int:id>', views.delete, name='delete'), path('update/<int:id>', views.update, name='update'), ]+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) this is my models.py class dish(models.Model): dish_id = models.AutoField dish_name = models.CharField(max_length=255, blank=True, null=True) dish_category = models.CharField(max_length=255, blank=True, null=True) dish_size = models.CharField(max_length=7, blank=True, null=True) dish_price = models.IntegerField(blank=True, null=True) dish_description = models.CharField(max_length=255, blank=True, null=True) dish_image = models.ImageField(upload_to="media/", default=None, blank=True, null=True) dish_date = models.DateField() def __str__(self): return self.dish_name `