Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve Server Error 500 on heroku
I am testing with django and created a simple app which would return some details about a given registration number. I compare those details with the lists of products i have in my shopify store and i would like to return filtered product which match the criteria. However Heroku serves with Server Error 500. I cant find anything wrong with the logs. 2021-07-31T20:43:09.115353+00:00 heroku[web.1]: Starting process with command `gunicorn APImat.wsgi --log-file -` 2021-07-31T20:43:11.691200+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [4] [INFO] Starting gunicorn 20.1.0 2021-07-31T20:43:11.692898+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [4] [INFO] Listening at: http://0.0.0.0:51130 (4) 2021-07-31T20:43:11.693005+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [4] [INFO] Using worker: sync 2021-07-31T20:43:11.697003+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [7] [INFO] Booting worker with pid: 7 2021-07-31T20:43:11.759836+00:00 app[web.1]: [2021-07-31 20:43:11 +0000] [8] [INFO] Booting worker with pid: 8 2021-07-31T20:43:12.235949+00:00 heroku[web.1]: State changed from starting to up 2021-07-31T20:43:13.000000+00:00 app[api]: Build succeeded 2021-07-31T20:43:29.513759+00:00 app[web.1]: VOLKSWAGEN 2021-07-31T20:43:29.513867+00:00 app[web.1]: SHARAN SEL BLUE TECH TDI S-A 2021-07-31T20:43:29.513923+00:00 app[web.1]: 0 2021-07-31T20:43:29.911010+00:00 app[web.1]: 6682466025621 2021-07-31T20:43:30.272828+00:00 app[web.1]: 6714350698645 2021-07-31T20:43:30.613893+00:00 app[web.1]: 6720035750037 2021-07-31T20:43:30.987627+00:00 app[web.1]: 6734793212053 2021-07-31T20:43:31.383095+00:00 app[web.1]: 6793971859605 2021-07-31T20:43:31.671587+00:00 app[web.1]: 6973133750421 2021-07-31T20:43:31.917019+00:00 app[web.1]: 10.41.181.68 - - [31/Jul/2021:20:43:31 +0000] "GET /KM12AKK/ HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36" 2021-07-31T20:43:31.919827+00:00 heroku[router]: at=info method=GET … -
Django Bootstrap collapse list not working properly and expanding all items
I am using bootstrap collapse element in my template but the problem is when I click on any items its' expanding all items. When I am adding pk inside html elements then it's not expanding. here is my code: html: {% for i in contact%} <p> <button class="btn btn-primary" type="button" data-toggle="collapse" data-target=".multi-collapse{{i.pk}}" aria-expanded="false" aria-controls="multiCollapseExample1{{i.pk}} multiCollapseExample2">Your Ticket Status</button> </p> <div class="row"> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample1{{i.pk}}"> <div class="card card-body"> {{i.message}} my replay.{{i.id}} </div> </div> </div> <div class="col"> <div class="collapse multi-collapse" id="multiCollapseExample2{{i.pk}}"> <div class="card card-body"> admin replay </div> <textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="write details about your project"></textarea><br> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </div> {%endfor%} models.py class Contact(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) parent =models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='contact_parent') #others fields -
HTML page loading a totally blank screen
<html lang="en"> <head> <title>Is it New Year's</title> </head> <body> {% if newyear %} <h1>YES</h1> {% else % } <h1>NO</h1> {% endif %} </body> </html> When I try running this HTML code I don't get an error but do get just a blank page when I should be getting either a yes or a no. Running this server using Django. -
502 Bad Gateway nginx/1.4.6 (Ubuntu)
I had website which is running using Django and it is working using nginx. I had tried to install SSL on the website, but it didn't succeed. But now when I try to access the website , it is giving me this error: 502 Bad Gateway nginx/1.4.6 (Ubuntu) What should I do ? thank you -
Django Authentication Classes via simple JWT apply locally to view but not on Elastic Beanstalk Production Server
I'm having trouble with some JWT authentication from the rest_framework_simplejwt package in relations to my django rest framework being deployed on Amazon Elastic Beanstalk in the Linux 2 Enviornment. This is what I have for my code: Technology Python 3.8 running on 64bit Amazon Linux 2/3.3.2 Relevant Pip Packages djangorestframework==3.12.4 djangorestframework-simplejwt==4.7.2 gunicorn==20.1.0 Views.py from django.shortcuts import render from rest_framework import generics from .serializers import ThingSerializer # Create your views here. from .models import Thing from rest_framework.permissions import IsAuthenticated class ThingView(generics.ListCreateAPIView): permission_classes = (IsAuthenticated,) queryset = Thing.objects.all() serializer_class = ThingSerializer settings.py INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'thing', 'rest_framework_simplejwt', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } urls.py from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt import views as jwt_views from . import views from files.views import ThingView urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', jwt_views.TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), path('jwt/test/', ThingView.as_view(), name='other-view'), ] When I run it locally, it works properly all the views work and the view that requires authentication (the ThingView) is working properly. However when I deploy my backend to my Amazon Elastic … -
Save reversal relationship item in database using one POST - Django
I have these models, serializers, and views: Models: class Connection(models.Model): from portfolio.models import Portfolio user = models.ForeignKey(User, related_name='exchange_connections', on_delete=models.CASCADE) class ConnectionSettings(models.Model): exchange_connection = models.OneToOneField(Connection, to_field='id', primary_key=True, related_name='settings', on_delete=models.CASCADE) import_past_transactions = models.BooleanField(default=False, blank=True) class ConnectionCredentials(models.Model): exchange_connection = models.OneToOneField(Connection, to_field='id', primary_key=True, related_name='credentials', on_delete=models.CASCADE) key = models.CharField(max_length=300, blank=False, null=False) secret = models.CharField(max_length=300, blank=False, null=False) passphrase = models.CharField(max_length=300, blank=True, null=True) Serializers: class ConnectionCredentialsSerializer(FlexFieldsModelSerializer): class Meta: model = models.Connection fields = '__all__' class ConnectionSettings(FlexFieldsModelSerializer): class Meta: models = models.ConnectionSettings fields = '__all__' class ConnectionSerializer(serializers.ModelSerializer): portfolios = PortfolioSerializer(many=True) credentials = ConnectionCredentialsSerializer(many=False) settings = ConnectionSettings(many=False) class Meta: model = models.Connection exclude = ('user',) read_only_fields = ('date_created', 'last_updated') Views: class ConnectionViewSet(viewsets.ModelViewSet): serializer_class = serializers.ConnectionSerializer queryset = models.Connection.objects.all() permission_classes = (IsAuthenticated, core_permissions.IsMineOnly) def get_object(self): return self.request.user.connections_set def perform_create(self, serializer): serializer.save(user=self.request.user) GET request works great and I get all values from the OneToOne relationships. However, when I create a connection, I want to be able to create all the rows associated using one request. For example, passing all the data needed for the different models in one POST request. -
django enumerate a model's integer field when another model gets created
from django.db import models class Game(models.Model): description = models.TextField(max_length=8192) class GamePreview(models.Model): game = models.OneToOneField(Game, on_delete=models.CASCADE) comments = models.IntegerField(default=0) # Want to + 1 this when a comment gets created class GameComment(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) comment = models.CharField(max_length=512) @classmethod # does not work def create(cls, game): comment = cls(game=game) preview = GamePreview.objects.get(game=comment.game) preview.comments += 1 return preview Basically, I have a GamePreview model that has a IntgerField that should show the amount of comments, but I cannot figure out how I can do preview.comments += 1 when a GameComment gets created... -
for loop doesn't work in Django template (inside of table tag)
i'm trying to create a table inside of my html template, but when i write <td>{{project.title}}</td> it doesn't work! actually when i use {{x}} i have no output! i don't really know what's wrong inside of my template... html template: {% extends 'main.html' %} {% block content %} <h1>Projects</h1> <table> <tr> <th>ID</th> <th>Project</th> <th>Votes</th> <th>Ratio</th> <th></th> </tr> {% for project in Projects %} <tr> <td>{{project.id}}</td> <td>{{project.title}}</td> <td>{{project.vote_total}}</td> <td>{{project.vote_ratio}}</td> <td>{{project.created}}</td> <td><a href="{% url 'project' project.id %}">View</a></td> </tr> {% endfor %} </table> {% endblock content %} models.py: from django.db import models import uuid from django.db.models.deletion import CASCADE # Create your models here. class Project(models.Model): title = models.CharField(max_length=200) descripeion = models.TextField(null=True, blank=True) demo_link = models.CharField(max_length=1000, null=True, blank=True) source_link = models.CharField(max_length=1000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self) -> str: return self.title class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote') ) # owner = project = models.ForeignKey(Project, on_delete=CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self) -> str: return self.value class Tag(models.Model): name = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) id = … -
Django AllAuth and dj-rest-auth custom user settings after Sign Up
I am using django-allauth and dj-rest-auth in my DRF project for social authentication. I have managed to set up the social authentication process, but I want to have a post-configuration for the user after the sign up. I want to set things up like full_name, is_verified etc. For now I only have this view that makes the authentication possible class AzureLoginView(SocialLoginView): adapter_class = AzureOAuth2Adapter client_class = OAuth2Client callback_url = 'http://localhost/login/azure/' I have a view that set this things up for a normal registrations, but I'm not sure how to integrate it with social registration. class AccountViewSet(mixins.CreateModelMixin, GenericViewSet): serializer_class = EmailUserSerializer permission_classes = [AllowAny, ] def perform_create(self, serializer): fullname = "something" # set other user parameters -
how to sort product by price low to high and high to low in django with fillters
i want to sort product list by pricing low to high and high to low and render in template my models.py class Item(models.Model): categories = models.ForeignKey(Categories, on_delete=models.CASCADE, related_name='our_items') subcategories = models.ForeignKey(Subcategories, on_delete=models.CASCADE, related_name='products') can_buy = models.ForeignKey(For, on_delete=models.CASCADE, related_name='for_wearing') name = models.CharField(max_length=200, blank=False) contain_size = models.CharField(max_length=50, blank=True) brand_name = models.CharField(max_length=100, blank=False, default='Bagh') first = models.ImageField(upload_to='items', blank=False) second = models.ImageField(upload_to='items', blank=False) third = models.ImageField(upload_to='items', blank=True) fourth = models.ImageField(upload_to='items', blank=True) fifth = models.ImageField(upload_to='items', blank=True) rating = models.FloatField(blank=False,default='4.0') item_video = models.FileField(upload_to='item_vedio', blank=True) color = models.CharField(max_length=30, blank=False, default='Black') material = models.CharField(max_length=50, blank=False, default='Plastic' ) return_policy = models.CharField(max_length=100, blank=False, default='7Days Return Policy') stock = models.CharField(max_length=50, blank=False, default='In Stock') price = models.FloatField(blank=False,) actual_price = models.FloatField(blank=False) type = models.CharField(blank=False, max_length=100, default='washable') about = models.CharField(blank=False,max_length=100, default='Lusturous') offer = models.CharField(max_length=4, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) description = models.TextField(blank=True) def __str__(self): return self.name here is my views.py class Product(View): def get(self, request, subcategory_id): subcategory = get_object_or_404(Subcategories, pk=subcategory_id) products = subcategory.products.all() category_list = Categories.objects.all() print(products) return render (request, 'products.html',{"subcategory_list" : products, 'category_list': category_list }) my html <div class="col-10"> <ul> <li class="filters"><strong>Sort By :</strong></li> <li class="filters"><a class="filter_by" href="">Popularity</a></li> <li class="filters"><a class="filter_by" href="">Price:--low to high</a></li> <li class="filters"><a class="filter_by" href="">Price:-- high to low</a></li> <li class="filters"><a class="filter_by" href="">Newest First</a></li> <li class="filters"><a class="filter_by" href="">Discount</a></li> </ul> … -
Django rest framework non_atomic_requests based on HTTP method
I am using Django Rest Framework and its class-based view, with database connection set to ATOMIC_REQUESTS=True. To optimize the application, I would like to have it so that only PUT and POST requests are under transaction, but not GET. Since I have ATOMIC_REQUESTS on, the documentation says to use the decorator on the dispatch() method in the view. So this is what I tried: class MyView(APIView): def get(): print("I am in a transaction:", not transaction.get_autocommit()) return Response({}) def post(): print("I am in a transaction:", not transaction.get_autocommit()) return Response({}) def put(): print("I am in a transaction:", not transaction.get_autocommit()) return Response({}) def dispatch(self, request, *args, **kwargs): """Override dispatch method and selectively apply non_atomic_requests""" if request.method.lower() == "get": return self.non_atomic_dispatch(request, *args, **kwargs) else: return super().dispatch(request, *args, **kwargs) @transaction.non_atomic_requests def non_atomic_dispatch(self, request, *args, **kwargs): """Special dispatch method decorated with non_atomic_requests""" return super().dispatch(request, *args, **kwargs) This does not work, since the get method still reports itself as under transaction, however, if I switch the decorator to look like this: ... @transaction.non_atomic_requests def dispatch(self, request, *args, **kwargs): if request.method.lower() == "get": return self.non_atomic_dispatch(request, *args, **kwargs) else: return super().dispatch(request, *args, **kwargs) def non_atomic_dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) ... This works, though obviously it's not … -
Why are data from json and inputted string different in my REST API SERVER?
I made a rest api with django. They are django server codes in urls.py urlpatterns = [ path('getchatid/<str:client_pk>/', giveCHAT_ID), ] And my client code by python give requests to my server with these codes.. def getChatid(pk): url = BASE_URL_FOR_GET_CHAT_ID + pk response = requests.get(url) if response.status_code == 200: temp = response.json()['chat_id'] modifyJson('BASIC_INFO', 'CHAT_ID', str(temp)) return True else: return False and json_data = readjson(isfileindoc()) client_pk = json_data["BASIC_INFO"]["PK_CLINET"] getChatid(client_pk) so I tested the code, getChatid like this ('1234QWER is a example of client_pk data') getChatid('1234QWER') it works in server, but It doesn't work with data read from json file... and I tried like this... but it didn't work temp = client_pk.replace('\t', '').replace('\n', '').replace(' ', '') getChatid(temp) how can i fix it? -
How do I achieve the equivalent of LEFT JOIN in Django - Nested Serializers in Django
I have the model specification below. MailingList is a reference table/model between Customer and Email. It has several other attributes, that will be useful in applying filters. My goal is to apply some filters then return serialized results. The results should include the customer's orders. models.py class Email(models.Model): name = models.CharField(max_length=300, unique=True) class Item(models.Model): name = models.CharField(max_length=50) class Customer(models.Model): passport_number = models.CharField(max_length=20, unique=True) name = models.CharField(max_length=20) class Order(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class MailingList(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) email = models.ForeignKey(Email, on_delete=models.CASCADE) serializer.py class CustomerSerializer(serializers.ModelSerializer): passport = serializers.CharField(source='customer.passport_number') customer_name = serializers.CharField(source='customer.name') # I want to add the orders for each customer too class Meta: model = MailingList fields = ['passport', 'customer_name'] views.py class CustomerViewSet(viewsets.ViewSet): def list(self, request): queryset = MailingList.objects.filter(some_filters).prefetch_related('customer') serializer = CustomerSerializer(queryset, many=True) return serializer.data Here's the response I'm currently getting [ {passport: 48, name: "Collins"}, {passport: 32, name: "Kate"} ] And here's the response I'm trying to get [ {passport: 48, name: "Collins", orders: {"1": "Hp EliteDisplay", "2": "Sony a7iii"}}, {passport: 32, name: "Kate" orders: {}} ] QUESTION: How do I embed orders within the same response? -
Notion type table save to database
As some of you may be aware, notion has the ability for users to create their own table with speicific fields. With the project that I am interested in doing, I am finding it hard to find a tutorial or for somebody to have the same question as me. What I am asking is: How would I go about creating a table that the end-user can create and add different dynamic colums to a table and for that to save on the database??? I have tried using a chrome web extension to show me the technologies that notion used to maybe get some idea but to be honest, I have none. Anyone with any answer will be much appreciated. Thanks in advance :) -
What is the correct way to post images on django-rest-framework server using javascript?
I have a POST API view that accepts an image and a style sting and returns a styled image. It works on postman just fine but I cannot get it to work using fetch API. Serializer: class GetImageSerializer(serializers.Serializer): image = serializers.ImageField() style = serializers.CharField() DRF view: class PostImage(APIView): serializer_class = GetImageSerializer parser_classes = [MultiPartParser] def post(self, request, format=None): print(request.data) # Debug img = request.data.get('image') # Process response = FileResponse(img) return response The fetch call: json = {} json["image"] = this.state.image json["style"] = "models\\wave\\wave200.pth" console.log("sending --- ", json) //debug fetch('/style_transfer/style/', { headers: { "Content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" }, body: json, method: "POST" } ).then(response => { if (!response.ok) { console.log("couldn't fetch image") } return response.json() }) .then(data => { console.log("fetched data") console.log(data) outputs of console logs. This shows that the correct data is in json dictionary But the data isn't received by DRF server. The print(request.data) from the view returns <QueryDict: {}>. The strange part is that the same code works with postman. Things I've tried: Remove the headers from fetch request - This throws unsupported media type error Set content-type to "application/json" - This reads the string parameter but image key is empty. this is what request.data looks like {'image': {}, … -
django chart.js can't use {{% for loop%}}
I am a newbie to django, I don’t know why I can use for loop in javascript in other people’s teaching, but I can’t use for loop in javascript like this. Hope someone can tell me why. enter image description here -
Django Default user model TypeError at /auth/users/ create_user() missing 1 required positional argument: 'username'
When I request to create a user using djoser Endpoint /user/. But it says create_user() missing 1 required positional argument: 'username' I am using postman to post the request and I am passing the username as you can see below: I don't know where the problem lies. I have also changed "username" to "name" but it did not work. Any help would be highly appreciated .Thank you very much 😊❤️❤️❤️. I will show you what you will ask me to show. -
Unknown error while retrieving django queryset objects from redis
In the below code snippet, I am trying to bring the cached objects from redis , while doing it facing the below error The use case is caching the top 30 comment objects at the 1st API call , so the when the API is called for 2 nd time, the cached objects will be passed to serialzers , avoiding the querysets Caching the comments objects featured=StockUserComments.objects.filter(some condition) qs=StockUserComments.objects.filter(some condition) latest=StockUserComments.objects.filter(some condition) all =list(chain(featured,qs,latest)) redis_client.set("feeds:top_comments", str(all[:30]),ex=1800) retrieving the objects top_comments = redis_client.get("feeds:top_comments") if top_comments: print("from cache") all = ast.literal_eval(top_comments.decode("utf-8")) error Traceback (most recent call last): File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "E:\stocktalk-api-platform\apps\stock_dashboard\views.py", line 748, in get all = ast.literal_eval(top_comments.decode("utf-8")) File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\ast.py", line 59, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "C:\Users\Fleetstudio\AppData\Local\Programs\Python\Python38\lib\ast.py", … -
Django queryset filter by 6 hour interval
I have a model class TestRequest(models.Model): created_at = models.DateTimeField(auto_now_add=True) is_accepted = models.BooleanField(default=False) What i want is to send an email to admin if the TestRequest is not accepted in every 6 hours once request created. How can i query the data in the cron function (which is running every minute) where i can fetch all the TestRequest which fall in the 6 hour interval and email to admin. -
Store Auto Generated Username into Database DJango
I am creating a registration form that accepts the end-user's Firstname, Lastname, email, and password. the program is designed to auto-generate a username. I have created a function that auto generates a unique username; however, I am new to Django and unsure how to get my auto-generated username to store into the database along with the user's info. Currently, the program is storing the user's manually input info. -
display data in multiple columns with for loop
I'm sure this is a simple answer but for the life of me I cant figure / find out how to go about this. I want to display blog posts from my data base in three equal columns. When I start looking into the bootstrap docs this is the code given. <div class="container"> <div class="row"> <div class="col-sm"> One of three columns </div> <div class="col-sm"> One of three columns </div> <div class="col-sm"> One of three columns </div> </div> </div> However If I go to implement it I dont understand how i would be able to put the for loop on it without it repeating everything 3 times. IE: {% for post in posts.all %} <div class="row"> <div class="col-sm"> <img class="post-image" src="{{ post.image.url }}" /> </div> <div class="col-sm"> <img class="post-image" src="{{ post.image.url }}" /> </div> <div class="col-sm"> <img class="post-image" src="{{ post.image.url }}" /> </div> </div> {% endfor %} If you could please point me in the right direction on how to go about this it would be very much appreciated bootstrap is not a requirement. -
Django deployment Failed to load resource: the server responded with a status of 404 (Not Found)
I have some product pictures uploaded in media folder that displays fine in development server, but after deployment I receive the 404 ressource not found error. In settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'node_modules')] STATIC_ROOT = os.path.join(BASE_DIR, 'productionStatic') STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' In urls.py from django.contrib import admin from django.urls import path from index import views from index.views import indexPage, hdnytorv from webshopRestaurant.views import hd2900_webshop_Main, AddressCheckForDeliverability, ChangeItemQuantity from webshopCustomer.views import TakeawayCheckout, totalPriceDeliveryPossible, DeliveryForm, PickUpForm, localDeliveryCheckoutAddressCheck, Payment, PaymentComplete from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = [ path('admin/', admin.site.urls), path('', indexPage.as_view(), name = 'index'), path('hdnytorv', hdnytorv.as_view(), name='hdnytorv'), path('hd2900', views.hd2900.as_view(), name='hd2900'), path('hd2900_takeaway_webshop', hd2900_webshop_Main.as_view(), name="hd2900_takeaway_webshop"), path('check-address-for-deliverable', AddressCheckForDeliverability.as_view()), path('changeItemQuantityInBasket', ChangeItemQuantity.as_view()), path('isPriceAboveDeliveryLimit', totalPriceDeliveryPossible.as_view()), path('hdbynight', views.hdbynight.as_view(), name='hdbynight'), path('takeawayCheckout', TakeawayCheckout.as_view()), path('deliveryFormCheckout', DeliveryForm.as_view()), path('pickupFormCheckout', PickUpForm.as_view()), path('local_delivery_checkout_is_address_deliverable', localDeliveryCheckoutAddressCheck.as_view()), path('localDeliveryPayment', Payment.as_view()), path('paymentComplete', PaymentComplete.as_view()), ] #When in production medida url must always be added to urlpatterns #if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) To display the product in view I have in my html template <img class="card-img embed-responsive-item" src="{% get_media_prefix %}{{ item.product.image_path }}" alt="{{item.meta_description}}"> The pictures are uploaded to this location django_project_folder/media/productImages. I have assured that it is owned by www-data group and also media and all … -
function create_user in CustomUserManager didn't work
I create a custom user model and manager but the create_user function in manager doesn't work. what is my fault? this is my model: class User(AbstractUser): email = models.EmailField(null = True, blank = True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) phone_number = models.BigIntegerField(unique=True) is_owner = models.BooleanField(default=False) is_advisor = models.BooleanField(default=False) name = models.CharField(max_length=40, null = True, blank = True) image = models.ImageField(blank = True, null=True) data_join = models.DateTimeField(default = timezone.now) code_agency = models.IntegerField(null=True, blank=True, default=0) opt = models.IntegerField(null = True, blank = True) is_verified = models.BooleanField(default = False) USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = UserCustomManager() def __str__(self): return str(self.phone_number) class Meta: verbose_name = 'user' verbose_name_plural = 'users' and this is my manager: class UserCustomManager(BaseUserManager): use_in_migrations = True def _create_user(self, phone_number, **extra_fields): if not phone_number: raise ValueError('The given phonenumber must be set') print(""" ======================== ======================== ======================== """) user = self.model(phone_number=phone_number, username=phone_number, **extra_fields) user.set_password("green") # Token.objects.create(user=user) user.save(using=self._db) return user def create_user(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) digits = "0123456789" print(""" ======================== ======================== ======================== """) OTP = "" for i in range(4) : OTP += digits[math.floor(random.random() * 10)] extra_fields.setdefault('opt', OTP) return self._create_user(phone_number, **extra_fields) def create_superuser(self, phone_number, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser … -
Angular app keeps saying _user is not defined
I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/ However, I'm trying to run the app to test the join page but it keeps saying property not defined in the constructor which is from the state.service.ts file. import { Injectable } from '@angular/core'; export declare interface User { token: string; apiKey: string; username: string; } @Injectable({ providedIn: 'root', }) export class StateService { constructor() {} private _user: User; get user(): User { return this._user; } set user(user: User) { this._user = user; } } -
i got an error stating that === Cannot assign "'12'": "Cart.product" must be a "Product" instance. please do help me out in solving the issue
I have attached an image of my code where you can find the add-to-cart function and the error is on line===23