Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you fix favicon and manifest image issue while building Python Django Website?
I am fairly new to coding and I'm doing this course where they teach you to build your own portfolio website suing python django. So far, everything has been going great. Everything loads perfectly except for my images whenever I upload them to the admin. They do not show up on the main site. Stackoverflow does not allow me to upload images yet. They only let me do a link. I'll copy both the text and the image link. This is my settings file: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR This is my URLs file: from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static import jobs.views urlpatterns = [ path('admin/', admin.site.urls), path('', jobs.views.homepage, name='home') ] urlpatterns += static(settings.STATIC_URL, document_ROOT = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_ROOT = settings.MEDIA_ROOT) This is what I have in my HTML code right now. <div class="container"> <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for job in jobs.all %} <!-- Row 1 Box 1 ================== --> <div class="col"> <div class="card shadow-sm"> <img class="card-img-top" src="{{ job.image.url }}"> <div class="card-body"> <p class="card-text"> {{ job.summary }} </p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> … -
how to get average of two date fields
I want to subtract the time user's result object is created and the time user has registered. these are my models: class User(AbstractUser): id = models.AutoField(primary_key=True) created_at = models.DateTimeField(auto_now_add=True) username = models.CharField(unique=True, max_length=13) first_name = models.CharField(max_length=32, null=True, default=None) last_name = models.CharField(max_length=64, null=True, default=None) class Results(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateField(auto_now_add=True, blank=True, null=True) score = models.FloatField() in my views, I want something like this: (Sum of all Results.created dates - Sum of all User.created_at dates)/ len(all users). how can I achieve this? -
My search bar backend config is not properly responding to my condition statement
I am currently configuring(backend) my search-bar in my Django project to search the database. I've put an 'if or else' statement for when the user just clicks the search button without putting anything in the search-box. The 'if or else' statement seems not to be working properly because it ignores the 'if' part and goes straight to the else part. I've tried different ways to fix it but I seem to be failing. How do I rectify this. function openNav() { document.getElementById("mynavbar").style.display = "block"; } function closeNav() { document.getElementById("mynavbar").style.display = "none"; } .navbar{ position: absolute; height: 102px; width: 1136px; left: 69px; top: 39px; border-radius: 0px; } .nav-menu{ display: none; } .closebtn{ display: none; } .logo img{ position: absolute; height: 57.599998474121094px; width: 100px; left: 12px; top: 31px; border-radius: 0px; } .HOME{ position: absolute; height: 38.10988998413086px; width: 97.52754211425781px; left: 203.26788330078125px; top: 48.19781494140625px; border-radius: 0px; font-family: Poppins; font-size: 27px; font-style: normal; font-weight: 700; line-height: 41px; letter-spacing: 0em; text-align: left; /* background: #FFFFFF; */ } .ARTIST{ position: absolute; height: 38.10988998413086px; width: 105.85134887695312px; left: 328.64324951171875px; top: 48.19781494140625px; border-radius: nullpx; font-family: Poppins; font-size: 27px; font-style: normal; font-weight: 700; line-height: 41px; letter-spacing: 0em; text-align: left; /* background: #FFFFFF; */ } .ABOUTUS{ position: absolute; height: 38.10988998413086px; width: 142.14324951171875px; … -
How can I automatically create an approve/reject history when I approve a request or return item?
My process for this is for them to request an item through the project request view and is stored in the Activity model, if a request has been posted they can either approve or reject it using the request approve or request reject view. Now, I want to create a history table that automatically stores the approved or rejected status of a requested item after they approve/reject it, who approved/rejected it, when it was done. Models.py class Activity(models.Model): Item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True, limit_choices_to={'Quantity__gt': 0}) staff = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, limit_choices_to={'Quantity__gt': 0}) project_site = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True) Quantity = models.PositiveIntegerField(null=True, default=1, validators=[ MaxValueValidator(100), MinValueValidator(1) ]) date_created = models.DateTimeField(auto_now_add=True) is_draft = models.BooleanField(default=True) request_status = models.IntegerField(default=0, validators=[ MaxValueValidator(3) ]) return_status = models.IntegerField(default=0, validators=[ MaxValueValidator(3) ]) note = models.TextField(max_length=255, null=True) class Meta: verbose_name_plural = 'Item Request' def __str__(self): return f'{self.Item}' Views.py def project_request(request): activities = Activity.objects.all() returns = ReturnItem.objects.all() if request.method == 'POST': form = ActivityForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.staff = request.user instance.request_status = 2 instance.return_status = 2 instance.save() return redirect('project_request') else: form = ActivityForm() context={ 'activities' : activities, 'returns' : returns, 'form' : form, } template_name ='project-admin/project-request-items.html' return render(request, template_name, context) def request_approve(request, pk): activities = Activity.objects.get(id=pk) activities.request_status = 1 … -
Make fields in updateAccount mutation optional django graphql auth
I'm using the package django graphql auth to handle authentication in a Django/Graphql project. I'm trying to make the UPDATE_MUTATION_FIELDS optional so that it isn't obligatory to enter them when using the updateAccount mutation, but with no success. The relevant part in my settings.py looks like: GRAPHQL_AUTH = { 'LOGIN_ALLOWED_FIELDS': ['email', 'username'], 'ALLOW_LOGIN_NOT_VERIFIED': False, 'REGISTER_MUTATION_FIELDS': { 'email': 'String', 'username': 'String', 'display_name': 'String', 'country': 'String', 'birth_date': 'Date', }, 'REGISTER_MUTATION_FIELDS_OPTIONAL': { 'bio': 'String', 'gender': 'String', 'is_mod': 'Boolean' }, 'UPDATE_MUTATION_FIELDS': { 'display_name': 'String', 'country': 'String', 'birth_date': 'Date', 'gender': 'String', 'bio': 'String', 'is_mod': 'Boolean' } Relevant models.py: class User(AbstractBaseUser): is_mod = models.BooleanField(default=False) display_name = models.CharField(_('Full name'), max_length=50) country = CountryField(blank_label=_('(select country)')) birth_date = models.DateField() bio = models.CharField(max_length=150, blank=True) So I decided to use a custom form to explicitly set these fields as optional: from graphql_auth.forms import UpdateAccountForm class UpdateUserForm(UpdateAccountForm): # Mark fields as not required class Meta(UpdateAccountForm.Meta): pass def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in (fields := self.fields): fields[field].required = False And my user mutation looks like: class UpdateAccount(relay.UpdateAccount): form = UpdateUserForm class AuthRelayMutation(graphene.ObjectType): # update_account = relay.UpdateAccount.Field() update_account = UpdateAccount.Field() And finally, I use the mutation above as: # All Mutation objects will be placed here class Mutation(AuthRelayMutation, graphene.ObjectType): debug = … -
How can I show shop wise products?
I am using django rest framework to create an ecommerce api. I made api and trying to fetch data using http package for flutter and dart. I fetched the shops/restaurants but now i want to fetch shop wise product. I mean when I tap a shop/restaurant the product will be shown by shop. Here is my models.py: class Shop(models.Model): created_at = models.DateField(default=date.today) user = models.ForeignKey(User, on_delete=models.CASCADE) shop_name = models.CharField(max_length=255) shop_logo = models.ImageField(upload_to="images/") class Product(models.Model): created_at = models.DateField(default=date.today) shop = models.ForeignKey(Shop, on_delete=models.CASCADE) product_name = models.CharField(max_length=255) product_img = models.ImageField(upload_to="images/") regular_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) selling_price = models.DecimalField(decimal_places=2, max_digits=10, default=0.00) is_active = models.BooleanField(default=False) class Meta: ordering = ["-id"] def __str__(self): return self.product_name Here is my serializer for restaurant/shop and product: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ("shop", "product_name", "product_img", "regular_price", "selling_price") depth = 1 class GetRestaurantSerializer(serializers.ModelSerializer): class Meta: model = Shop fields = ("id", "shop_name", "shop_logo") depth = 1 Here is my views: class ShopView(APIView): def get(self, request): shop = Shop.objects.all() shop_serializer = GetRestaurantSerializer(shop, many=True) return Response(shop_serializer.data, status=status.HTTP_200_OK) class ShopWiseProducts(APIView): def get(self, request, shop_id): shopId = Shop.objects.get(id=shop_id) product = Product.objects.filter(shop=shopId.id) product_serializer = ProductSerializer(product, many=True) return Response(product_serializer.data, status=status.HTTP_200_OK) Here is my urls path("products/<int:shop_id>/", ShopWiseProducts.as_view()), path("shops/", ShopView.as_view()), Flutter Part In my flutter … -
How to update my Django database with rss feed every X minutes?
Am working new with RSS feed For every x minutes, i want to add things to my database from rss feed if it has any new things in that. I have written the code to fetch and update in database but how to make that code run for every X minutes. If i put the piece of code inside one of my views function which renders home page, it slows down the page loading speed. I want it to happen automatically every x minutes without affecting my website functionality. -
Reverse for 'dashboard_with_filter' not found. 'dashboard_with_filter' is not a valid view function or pattern name
urls file: urlpatterns = [ path('admin/', admin.site.urls, name='admin'), url(r"^accounts/", include("django.contrib.auth.urls")), path('dashboard/', show_dashboard, name='show_dashboard'), ] template base.html: <li><a class="nav-link " href="{% url 'show_dashboard' %}">Dashboard</a></li> views file: def show_dashboard(request): if request.method == 'GET': type= 'x' elif request.method == 'POST': type= request.POST['type'] return render(request, "dashboard/index.html", {'label': label, 'value': value, 'type': type} I am getting this error "Reverse for 'dashboard_with_filter' not found. 'dashboard_with_filter' is not a valid view function or pattern name" when clicking the Dashboard navigation link. -
Moving a Shiny app prototype to another platform?
I made a Shiny App for the non-profit I work at. It has great utility internally, and people are starting to make requests - there may even be funding to scale it commercially. My problem is that I am a biologist (using R for data analysis) with no proper CS background. I saw an opportunity to optimize something and learned Shiny on the fly, 'bandaging' my way to a now functional web app. Needless to say, it works well but it is a clunky nightmare - I learned on my own and probably made all the mistakes that a proper CS course would teach you not to make. I would like to start a small team and I was advised that for a professional production-ready Web App, something like Django would be ideal. I love Shiny because that's what I started with but I am ready to follow courses online and learn how to use Django. We need everything (server-side, authentication etc..). How easy is it to translate a Shiny App (or re-write it from scratch) using Django? Is Django what I have to use, or should I use Angular or other Javascript-only methods? Thank you in advance. Edit: It … -
Django rest framework custom permission for ViewSet
this is my modelViewSet class UserViewSet(viewsets.ModelViewSet): def list(self, request): users = User.objects.all() serializer = UserSerializer(users, many=True) return Response(serializer.data, status=status.HTTP_200_OK) def create(self, request): serializer = UserSerializer(data=request.data) if serializer.is_valid(raise_exception=True): pass def retrieve(self, request, pk): user = get_object_or_404(User, pk=pk) serializer = UserSerializer(user) return Response(serializer.data, status=status.HTTP_200_OK) def get_permissions(self): if self.action == "list": permission_classes = [ IsAdminUser, ] elif self.action == "create": permission_classes = [AllowAny] else: permission_classes = [AccountOwnerPermission] return [permission() for permission in permission_classes] and this is the custom permission class class AccountOwnerPermission(permissions.BasePermission): def has_object_permission(self, request, view, obj): print(object) print(request.user) return obj == request.user i access this view from another user and it show me user retrieve, and that 2 prints on AccountOwnerPermission won't run. can someone tell me what is wrong with what i did and why has_object_permission wont run. i change has_object_permission to has_permission and it works, but i dont have access to obj on the other hand -
Django Login Required Redirect
Im trying to redirect a user when he isn't logged in the my LoginPage. I Have Tried Many Different solutions - Like @login_required & request.user.is_authenticated - yet nothing worked... im leaving my views.py & urls.py so someone can see if they can spot the problem Thanks For Any Help! Views.Py: from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator # Create your views here. @login_required(login_url='/Login') def Dashboard(request): if request.user.is_authenticated: return render(request, 'home/index.html') else: return LoginPage(request) def LoginPage(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username, password=password) if user is not None: request.session.set_expiry(86400) login(request, user) return redirect('dashboard') return render(request,'accounts/login.html') def registerPage(request): form = UserCreationForm() if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, "Account Created for " + user + " Succesfully" ) return redirect('login') context = {'form': form} return render(request, 'accounts/register.html', context) def Admin(request): return HttpResponseRedirect(reverse('admin:index')) def Logout(request): authenticate.logout(request) logout(request) return LoginPage(request) Urls.Py: from django.urls import path from. import views from django.contrib import admin from django.urls import … -
Setting Timestamp in Python w/ timezonedb.com
I have an app that uses timezonedb to grab local timezone information when creating a new post, but I am not sure of the math in order to get the new posts to reflect the timezone where I am. For example, I am currently in South Africa, posted an update to my server (which is using UTC time), and the date/time on the post gives PST. I would love some help with the code here, as it may just be me being bad at math. At this time UTC: Wed Jan 26 05:33:09 UTC 2022 I made a post with timestampdb info: timestamp: 1643182360 dst: 0 offset: 7200 The post showed up on my app as 09:33pm yesterday (it was 7:33 am here). I am normally based in California, so I'm not sure if there is something I can do to fix this. In my Django settings app, I am using "TIME_ZONE = US/Pacific" and "USE_TZ = True" In my views: def post(self, request, *args, **kwargs): if data['timestamp'] != '': offset = data['tz_offset'] timestamp = data['timestamp'] if timestamp != '' and offset != '': if int(offset) < 0: timestamp = int(data['timestamp']) + abs(int(offset)) else: timestamp = int(data['timestamp']) - abs(int(offset)) naive_time … -
local 'variable' referenced before assignment
I wrote a signal that changes a field inside user model. it works fine but when a user registers for the first time it gives me this error: UnboundLocalError: local variable 'scientific' referenced before assignment this is my signal: @receiver(pre_save, sender=User, dispatch_uid='progress_change') def progress(sender, instance, **kwargs): user = instance if ScientificInfo.objects.filter(user=user).exists(): scientific = ScientificInfo.objects.get(user=user) if ReligiousInfo.objects.filter(user=user).exists(): religious = ReligiousInfo.objects.get(user=user) if PsychologicInfo.objects.filter(user=user).exists(): psychological = PsychologicInfo.objects.get(user=user) if InvestigationInfo.objects.filter(user=user).exists(): investigation = InvestigationInfo.objects.get(user=user) if scientific.is_interviewed == False and religious.is_interviewed == False and psychological.is_interviewed == False and investigation.is_interviewed == False: user.progress_level = USER_PROGRESS_LEVELS[1][0] if scientific.is_interviewed == True and religious.is_interviewed == False and psychological.is_interviewed == False and investigation.is_interviewed == False: user.progress_level = USER_PROGRESS_LEVELS[2][0] if scientific.is_interviewed == True and religious.is_interviewed == True and psychological.is_interviewed == False and investigation.is_interviewed == False: user.progress_level = USER_PROGRESS_LEVELS[3][0] if scientific.is_interviewed == True and religious.is_interviewed == True and psychological.is_interviewed == True and investigation.is_interviewed == False: user.progress_level = USER_PROGRESS_LEVELS[4][0] if scientific.is_interviewed == True and religious.is_interviewed == True and psychological.is_interviewed == True and investigation.is_interviewed == True: user.progress_level = USER_PROGRESS_LEVELS[5][0] I think the pre_save is causing the issue because when I change it to post_save users can register but the signal wont work then. what should I do to fix this problem? -
Account activation using Django on newest Safari not working
I have run into a weird issue using Djoser for account activation. My web app successfully allows you to sign up for an account and sends you an activation email for your account. However, when entering the activation link sent to my email in Safari I receive a 401 (unauthorized). When entering the activation link in Chrome, it successfully activates the account. Why might this be occurring? It should also be noted that I have everything Dockerized and running through NGINX. If I locally run my React app using npm start, and then add :3000 to the activation URL I receive, also works successfully to activate the account in Safari. For example, if I receive http://localhost/activate/xyz/abcdef as an activation email, editing it to http://localhost:3000/activate/xyz/abcdef and entering that URL into Safari while the React app is running locally it successfully activates the account. My settings.py has this configuration for Djoser: DJOSER = { "USER_ID_FIELD": "username", "LOGIN_FIELD": "email", "SEND_ACTIVATION_EMAIL": True, "ACTIVATION_URL": "activate/{uid}/{token}", "PASSWORD_RESET_CONFIRM_URL": "reset_password/{uid}/{token}", 'SERIALIZERS': { 'token_create': 'apps.accounts.serializers.CustomTokenCreateSerializer', }, } PROTOCOL = "http" DOMAIN = "localhost" if not DEBUG: PROTOCOL = "https" DOMAIN = "domain.com" EMAIL_HOST = 'smtp.gmail.com' DEFAULT_FROM_EMAIL = 'Don\'t Reply <do_not_reply@' + DOMAIN + '.com>' EMAIL_HOST_USER = 'xyz@gmail.com' EMAIL_HOST_PASSWORD = … -
chat database structure and perform sided deletion in drf
I have researched and was not able to find the correct answer I decided to ask questions here. I have a chat application in Django Rest the structure is as follows: Chat Table this is both for Group and Private. It contains from_user, to_user columns for private chats. title column for group chats Chat Member Table in this table group, chat users are saved at last Message Table my first question is that is it a good structure for the whole chat app? what do I need to do to perform one-sided deletion? for example, if user A deletes a message or chat, user B or remained chat users should be able to see the message or chat Can anybody give me advice, please? -
How to Convert Api view class to CreateModelMixin
class Add_Product(APIView): def post(self,request,*args, **kwargs): user=request.user if user.is_authenticated: data=request.data date=datetime.now().date() slug=user.username+"-"f'{int(time())}' print(data) serializer=ProductSerializer(data=data,many=True) if serializer.is_valid(): print(serializer.data) serializer.save(user=request.user,slug=slug) return Response("Your product is added") return Response(serializer.errors) return Response("Login First") I want to convert this to CreateModelMixin But i don't know how to pass values like request.user and slug in create method. class Product_List(GenericAPIView,CreateModelMixin): queryset = Product.objects.all() serializer_class = ProductSerializer def post(self,request,*args, **kwargs): return self.create(request,*args,**kwargs) -
graphene-django full text search
I'm struggling with implementing full text search with graphene-django module. Is there a way to do this? (I'm using relays). I want to pass search string to my get query as an additional field. Which search engine to use is not important. Haven't found any useful information -
How can I solve this KeyError
How to solve this?? Is anything wrong there?? I'm new to Django... Thanks in advance -
Django View that shows related model context
I'm learning and I'm struggling to create a Django view that displays a Company Detail model, but also can show the associated location names that are located in child FK models to the Company. What I've tried includes these models: class Company(models.Model): company_name = models.CharField(max_length=100, unique=True) street = models.CharField('Street', max_length=100, null=True, blank=True) city = models.CharField('City', max_length=100, null=True, blank=True) province = models.CharField('Province/State', max_length=100, null=True, blank=True) code = models.CharField('Postal/Zip Code', max_length=100, null=True, blank=True) company_comments = models.TextField('Comments', max_length=350, null=True, blank=True) class Region(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) region_name = models.CharField(max_length=100) description = models.TextField(blank=True) def __str__(self): return self.region_name class District(models.Model): region = models.ForeignKey(Region, on_delete=models.CASCADE) district_name = models.CharField(max_length=100) description = models.TextField(blank=True) dictrict_ops_leadership = models.CharField(max_length=100, blank=True) def __str__(self): return self.district_name My view looks like: class CompanyDetailView(DetailView): model = Company template_name = 'main/company_detail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['region'] = Region.objects.all() context['district'] = District.objects.all() return context I want to call **all instances of Region and District** for the **single instance of Company.** With my HTML tags as : <p>{{ region }}{{ district }}</p> It just returns a list of query's of all Region and District instances: <QuerySet [<Region: RegionA>, <Region: RegionB>]> <QuerySet [<District: DistrictA>, <District: DistrictB>]> Any help would be GREATLY appreciated. Thanks -
Django ignores second value of input form field
When I submit a form, one of the inputs has multiple values, but Django ignores the values and just takes the first one. request.POST: <QueryDict: {'csrfmiddlewaretoken': ['2hM...truncated'], 'project_code': ['123'], 'project_manager': ['Michael Jackson', 'Hulk Hogan'], note': ['']}> So, I would like to have in my db for the column project_manager the value Michal Jackson,Hulk Hogan but instead I'm only getting Michael Jackson. models.py: class Project(models.Model): project_code = models.CharField(max_length=250, null=False, blank=False) project_manager = models.CharField(max_length=250, null=True, blank=True) note = models.CharField(max_length=2000, null=True, blank=True) forms.py: class CreateNewProjectForm(ModelForm): class Meta: model = Project fields = '__all__' -
400 Bad Request error from amazon S3 uploading
I am uploading the file to S3 pucket with this library django-s3direct https://github.com/bradleyg/django-s3direct I am trying to do the example of this library $ git clone git@github.com:bradleyg/django-s3direct.git $ cd django-s3direct $ python setup.py install $ cd example # Add config to your environment export AWS_ACCESS_KEY_ID='…' export AWS_SECRET_ACCESS_KEY='…' export AWS_STORAGE_BUCKET_NAME='…' export AWS_S3_REGION_NAME='…' export AWS_S3_ENDPOINT_URL='…' $ python manage.py migrate $ python manage.py createsuperuser $ python manage.py runserver When uploading the file,In my chrome console. there is 400 Bad Request. amazon s3 public access, Iam policy is set and S3 CORS is set. From this log, it looks authentification is finished??? Where should I check ? Starting myarshe.jpg reason: first file index.js:43 index.js:43 initiate getPayloadSha256Content: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 index.js:43 initiate V4 CanonicalRequest: POST /vr-dev-my-resource-bucket/myarshe.jpg uploads= content-type:image/jpeg host:s3.ap-northeast-1.amazonaws.com x-amz-acl:public-read x-amz-date:20220126T044825Z content-type;host;x-amz-acl;x-amz-date e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 index.js:43 V4 stringToSign: AWS4-HMAC-SHA256 20220126T044825Z 20220126/ap-northeast-1/s3/aws4_request 491645163177dd5166cf240fe4ad71a12424b2f358b7f453371d6c921d882d1f index.js:43 initiate signature: 61ac2bd7b3c323fd134e09f187921a2acdeadf6c722d9f1c43421d37ec7e482c index.js:43 initiate getPayloadSha256Content: e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 s3.ap-northeast-1.amazonaws.com/vr-dev-my-resource-bucket/myarshe.jpg?uploads:1 POST https://s3.ap-northeast-1.amazonaws.com/vr-dev-my-resource-bucket/myarshe.jpg?uploads 400 (Bad Request) -
Django module autocomplete not working in VSCode
I am learning Django. While creating a class that extends CreateView, I found that the module was not autocompleted in the VSCode environment. In case of HttpResponseRedirect, it is automatically completed as follows. enter image description here I get "from django.contrib.auth.models import User " is required, but does not appear in the autocomplete list. enter image description here I've been working on this issue for 3 hours now. Any help would be greatly appreciated. -
Django Template Aren't Loading
I'm trying to load different html files into the base.html and they're not showing. Any ideas? <body class="bg"> <main class='text'> {% block carousel %} {% endblock %} {% block info%} {% endblock %} {% block content %} {% endblock %} {% block mobile %} {% endblock %} </main> </body> -
Using Primary Key To Index HTML Template Django
Bit confused on how I would index a list I have based on the primary key in the HTML template? Here is my views page: def current_game_table(request): items = list(Nbav8.objects.using('totals').all()) return render(request, 'home/testing.html', {'items': items}) def current_games(request, pk): item = Nbav8.objects.using('totals').get(pk=pk) items2 = list(CurrentDayStats.objects.using('totals').values_list('home_team_over_under_field', flat=True)) return render(request, 'home/testing2.html', {'item': item, 'uuup':items2}) Here is my testing1.html: Hello World {{ items }} {% for item in items %} <a href="{% url 'current_games' item.pk %}">{{ item.home_team_field }}</a> {% endfor %} Here is my testing2.html: <p>The price of this item is: {{ item }}</p> Where is it?!!? {{ item.uuup }} My pages display fine testing1 shows my pages as I want for testing purposes, my problem is this. On my testing2.html page that displays, I have a list "uuup", my problem is, I only want to show uuup.0 on page 1, uuup.1 on page 2, uuup.2 on page 3, etc. I can't seem to figure out how to use the pk as an index? I set a diff variable in my views page and set it to int(item) and printed it out on each page to confirm that each subpage showed it as 1/2/3/4/etc so I am unsure how to call it to use … -
Heroku - Server Error (500) - Not Static - DEBUG = False
On my Django website, I am working on getting the final bugs out and I am running into an error. I finally got my static files to host using Whitenoise and they are hosting fine on the local server when DEBUG = True or False and they are hosting fine on in production on Heroku when DEBUG = True. I know that you can get a lot of the same 500 errors when static files are being hosted locally but I don't believe that I am getting these 500 errors from my static files anymore. I have been looking at the Heroku logs after the 500 errors come up and I haven't been able to narrow down the problem. I am hoping that someone can help me answer the following question. Why am I receiving Server Error (500) in Heroku when DEBUG = False. Thanks in advance!! settings.py: import django_heroku from pathlib import Path import os from django_quill import quill from inspect_list.security import * # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_DIR = os.path.dirname(BASE_DIR) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') #MEDIA_ROOT = os.path.join(BAS_DIR, 'media') TIME_INPUT_FORMATS = ['%I:%M %p',] #Media_URL = '/signup/front_page/sheets/' # Quick-start development settings …