Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display Maximum Discount Product in Django?
I have products table in my database, and there are two columns with totalprice and saleprice, when I am adding a product from backend I submit both prices. I want to calculate the maximum offer on the product (for calculate the offer logic will be something like this, offer=totalprice/saleprice), and I want to display those products on my website homegae, but I don't know how I can do it in Django. Please let me guide how I can add the logic in views.py file. here is my views.py file... def home(request): product= Product.objects.filter(featured=True).order_by('-created_at')[0:8] subc=Product.objects.filter(discount=30).order_by('-created_at') return render(request, 'mainpage/index.html', {'product':product,'subc':subc}) here is my models.py file class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ForeignKey('SubCategory', related_name='prosubcat', on_delete=models.CASCADE, blank=True, null=True) totalprice=models.IntegerField() saleprice = models.IntegerField() title=models.CharField(max_length=225) description = models.TextField() overview = models.TextField(null=True) featured = models.BooleanField(null=True) trending=models.BooleanField(null=True) image= models.ImageField(blank=True) tags = TaggableManager() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
'function' object has no attribute 'objects' Django AttributeError
This is my models: from django.db import models # Create your models here. class post(models.Model): title = models.CharField(max_length=255) body = models.TextField() date = models.DateTimeField(auto_now_add=True) and this is my views in django from django.shortcuts import render from .models import post from django.http import HttpResponse # Create your views here. def post(request, id): data = {'post': post.objects.get(id=id)} return render(request, 'post/post.html', data) I try to get post by id but error found: AttributeError at /post/3/ 'function' object has no attribute 'objects' -
How to mark Username with rest-auth in the DRF as a name instead of a number
I am going to use Django to receive the value of Arduino and serialize it into REST API. First of all, member management function was established with rest-auth and 'name' variable was designated as a foreign key to store sensor values for each user by creating an aduinos model. After running the server and logging in, I checked the API that contains the data of each user, and there was a number next to the name, not the user's username. I wonder how to change this to username instead of number. here is my code models.py class arduino (models.Model) : name = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) temp = models.FloatField() humi = models.FloatField() serializers.py class arduinoSerializers (serializers.ModelSerializer) : class Meta : model = arduino fields = ('name', 'temp', 'humi') views.py class arduinoViewSet (viewsets.ViewSet) : def dataSend (self, request) : queryset = arduino.objects.all() serializer = arduinoSerializers(queryset, many=True) return Response(serializer.data) please help me :( -
Python Crash Course Chapter 18: The Learning Log Home Page
I am working through chapter 18 in Python Crash Course by Eric Matthes, which is a tutorial on how to create web apps with Django. Currently I'm mapping a URL, writing a view, writing a template, and then trying to deploy the app on my system so I can see the homepage I created. Here are the relevant files/code: urls.py-learning_log from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls')) ] urls.py-learning_logs """Defines URL patterns for learning_logs.""" from django.urls import path from . import views app_name = 'learning_logs' url_patterns = [ # Home page path('', views.index, name='index'), ] views.py from django.shortcuts import render def index(request): """The home page for Learning Log.""" return render(request, 'learning_logs/index.html') index.html <p>Learning Log</p> <p>Learning Log helps you to keep track of your learning, for any topic you're learning about.</p> When I try to create the server using the runserver command from within the virtual environment for the project using Powershell for Windows, here's the error I get: (ll_env) PS C:\Users\Samie\Desktop\python_work\learning_log> python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Samie\Desktop\python_work\learning_log\ll_env\lib\site- packages\django\urls\resolvers.py", line 590, in url_patterns iter(patterns) TypeError: … -
Django celery not sending email
I'm trying to run this periodic task to send an email. On terminal I'm running "celery -A dash beat -l info" and "celery -A dash worker -l info" command. In my terminal I'm getting " Task accounts.tasks.send_email[33219fec-3655-4040-a036-e55c408696cc] succeeded in 10.002337335s: None " response , but I'm not receiving any email in my gmail. tasks.py @shared_task def send_email(email_id, message): time.sleep(10) print(f"Email is sent to {email_id}. Message sent was - {message}") celery.py app = Celery('dash') app.conf.beat_schedule = { 'add-every-5-seconds': { 'task': 'accounts.tasks.send_email', 'schedule': 1.0, 'args': ('dummyguy1680@gmail.com','This is sample message.') } } app.conf.timezone = 'UTC' settings.py EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER ='dummyguy1680@gmail.com' EMAIL_HOST_PASSWORD ='popmanthex' CELERY_BROKER_URL = 'amqp://myuser:mypassword@localhost:5672/myvhost' CELERY_TIMEZONE = 'UTC' CELERY_ENABLE_UTC = True CELERY_IMPORTS = ['accounts.tasks'] CELERY_EMAIL_TASK_CONFIG = { 'name': 'djcelery_email_send', 'ignore_result': True, } -
Getting text on image how?
**No error in this code** What I’m basically trying to do is get my text that says preapproved and put that onto my image the closest I got was I got my text behind the image but not on to my image. Was hoping I could get some help please and thank you. import React from ‘react’; import Car from ‘./car_lot.jpg’ import Header from ‘./logo.png’ import Paperwork from ‘./sign_documents.jpg' import Car_Galleryimg1 from './jeep.jpg' import Car_Galleryimg2 from './bmw.jpg' import Car_Galleryimg3 from './toyota.jpg' import ImageGallery from 'react-image-gallery'; const images = [ { original: Car_Galleryimg1, thumbnail: Car_Galleryimg1, }, { original: Car_Galleryimg2, thumbnail: Car_Galleryimg2, }, { original: Car_Galleryimg3, thumbnail: Car_Galleryimg3 }, ]; function Home() { return ( **Trying to get preapproved onto my image the closest I have gotten is getting the word preapproved behind my image but not onto it and that is what I’m trying to figure out** <div className=“home”> <img src={Header} className=“logo.png”/> <h1>Welcome to Exclusive Auto Sales</h1><link href=“https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap" rel="stylesheet"/> <h3>Get pre-approved!</h3><img src={Paperwork} className="sign_documents"/> <h2>Get your dream car today we are here to help you!</h2> <ImageGallery items={images} /> </div> ); } export default Home; -
How to write right query to call all posts related to a tag in Django views.py?
I want to show all posts associated with a particular tag in my blog. website. Can someone help me to do it, I think something wrong in my views query, i was trying to solve if for a whole week. This is my code: I am not sure how to write appropriate query for this in my view.py file. Thank you in advance views.py def topics(request): context = { 'posts': Post.objects.all() } return render(request,'blog/list_of_topics.html',context) ``` models.py ``` class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) class Priority(models.Model): prior_name = models.CharField(max_length=100) def __str__(self): return self.prior_name def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) class Post(models.Model): choices = Category.objects.all().values_list('name', 'name') choice_list = [] first=Priority.objects.all().values_list('prior_name','prior_name') prior_list=[] for i in first: prior_list.append(i) for i in choices: choice_list.append(i) #choices=(('s','small'),('m', 'medium')) title = models.CharField(max_length=100) #content = models.TextField() content = RichTextField(blank=True, null=True) priority=models.CharField(max_length=100,choices=prior_list, null=True) date_posted= models.DateTimeField(default=timezone.now) author =models.ForeignKey(User, on_delete=models.CASCADE) category=models.CharField(max_length=100,choices=choice_list) snippet=models.CharField(max_length=255, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) urls.py urlpatterns = [ path('', PostListView.as_view(), name="blog-home"), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name="post-detail"), path('post/new/', PostCreateView.as_view(), name="post-create"), path('post/<int:pk>/update/', PostUpdateView.as_view(), name="post-update"), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name="post-delete"), path('about/', views.about, name="blog-about"), path('mastering/',views.topics, name='blog-topics'), ] -
CORS policy block on setting session variable
I'm new to Django and currently developing an app with ReactTSX and Django. I'm using Django as my backend and whenever I try to assign a value to the request session variable I get the listed error. Login Page import Cookies from "js-cookie"; axios.request({ url: "login/", baseURL: window.BACKEND_BASEURL, method: "POST", data: data, timeout: 15000, withCredentials: true, headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": Cookies.get("csrftoken") }, validateStatus: () => true }).then((res: AxiosResponse): void => { http://localhost:8000/login/ def get(r): r.session["user_id"] = "ME" <-- Causing ERROR when assigning a variable settings.py .......... .......... CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ["GET","POST"] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with" ] .......... .......... Error Access to XMLHttpRequest at 'http://localhost:8000/login/' from origin 'http://localhost:5000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. -
Django 3 multiple forms in forms.py
I am new to django, I am trying to build multiple forms that will be in multiple class based views my forms.py looks like this from django import forms from .models import Photo class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file', ) class NewContactForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) And I was hoping for my view to be something like: ... from app_workflow.forms import PhotoForm, NewContactForm class NewContactView(View): def get(self, request): ... def post(self, request): form = NewContactForm(self.request.POST, self.request.FILES) if form.is_valid(): data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) class DragAndDropUploadView(View): def get(self, request): ... def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) However, when I add NewContactForm into the import of myapp.forms from app_workflow.forms import PhotoForm, NewContactForm I get the error: from app_workflow.forms import PhotoForm, NewContactForm ImportError: cannot import name 'NewContactForm' from 'app_workflow.forms' So i am not sure what is the best way to bring and be able to use that second form? -
URL navigation for django
Working on django with two apps, fundraiser and donations (using Stripe dummy API). Currently, a user must be logged in to create a fundraiser (/create), and you can view any one fundraiser (/show/id). The fundraiser's show page has a donate button. The Stripe API accepts payment, but it is agnostic of any specific fundraiser (/donate). How can I: format the donation app's URLs to show up as /show/id/donate) donate to that specific fundraiser Main App Settings INSTALLED_APPS = [ 'fundraisers.apps.FundraisersConfig', 'accounts.apps.AccountsConfig', 'donations.apps.DonationsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Main App URLs urlpatterns = [ path('', include('fundraisers.urls')), path('donate/', include('donations.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')) ] Fundraisers App Model class Fundraiser(models.Model): name = models.CharField(max_length=50) start_date = models.DateTimeField(auto_now=True, auto_now_add=False) end_date = models.DateTimeField(auto_now=False, auto_now_add=False) current_total = models.IntegerField(default=0) goal = models.IntegerField(default=0) def __str__(self): return self.name def expired_fundraiser(self): return self.end_date <= timezone.now() Fundraisers App Views def index(request): fundraisers = Fundraiser.objects.all() return render(request, 'fundraisers/index.html', { 'fundraisers': fundraisers }) def create(request): if request.method == "POST": name = request.POST['name'] end_date = request.POST['end_date'] goal = request.POST['goal'] fundraiser = Fundraiser.objects.create( name=name, end_date=end_date, goal=goal ) fundraiser.save() id = fundraiser.id if id is not None: return redirect(f'/show/{id}') else: return render(request, 'fundraisers/index.html') else: return render(request, 'fundraisers/create.html') def show(request, id): fundraiser = Fundraiser.objects.get(pk=id) … -
Django: Real-time data processing to broadcast to users over channels
Imagine a system where each user's integer input changes all users' output. Output data example: user input rank (largest to smallest) average input of all users number of unique inputs sum of all inputs number of users live number of users with at least one input Everything must be in real-time, so that lends itself perfectly to using a web socket with Django channels. However, there is a lot of data manipulation and statistics to calculate and all stats must be broadcasted back to users in real time. How and where can I do all these data calculations in Django? I need something that continuously fetches and manipulates data from the UserInput model and sends a resulting JSON to the channel for broadcast to all users connected to the WebSocket in a non-blocking fashion. Doing this in the channel itself seems excessive. Doing it through a new model which updates doesn't work for some of the data I am looking for. E.g. rank would have to be a derived field or an ordered list. Haven't found any resources for doing derived fields in models. In my research, I found people recommending Tornado, or a company running auctions that used Firebase, … -
permission doesn't work in view method [Django restframework]
I'm using django restframework to do some permission requiring work. What I want to do is make a whole permission require in my view and a different permission require in my specified method. And below is my trial with some main codes. 1 basic view class VSAccount(viewsets.ModelViewSet): queryset = MAccount.objects.all().filter(active=True) serializer_class = DEFAULT_ACCOUNT_SERIALIZER_CLASS filter_backends = (SearchFilter, DjangoFilterBackend) permission_classes = [IsAuthenticated, BaseDataPermission, ] filter_class = FAccount search_fields = [] module_perm = 'account.get_account' # 1) add module_perm account.get_account required for whole view. @action(methods=['get'], url_path='list-with-daily-spends', detail=False) def list_daily_spend(self, request, *args, **kwargs): self.module_perm = 'account.get_account-list-with-daily-spend' # 2) add module_perm for this method only but doesn't work here self.permission_classes = [BaseDataPermission, ] self.serializer_class = SAccountListItemDaily ret_data = super().list(request, *args, **kwargs) self.serializer_class = DEFAULT_ACCOUNT_SERIALIZER_CLASS return ret_data 2 customer permission class BaseDataPermission(BasePermission): authenticated_users_only = True def has_perms(self, user, perm): user_perms = user.get_all_permissions() print(perm) # it's always what I write in viewset? if perm in user_perms: return True return False def has_permission(self, request, view): if request.user.is_superuser: return True assert hasattr(view, "module_perm"), "need module_perm" assert isinstance(view.module_perm, str), "module_perm should be a string" if getattr(view, '_ignore_model_permissions', False): return True if hasattr(view, 'get_queryset'): queryset = view.get_queryset() else: queryset = getattr(view, 'queryset', None) assert queryset is not None, ( 'Cannot apply DjangoModelPermissions … -
djanago channels CRITICAL Listen failure: Couldn't listen on 0.0.0.0:x: [Errno 98] Address already in use
I am trying to deploy my ASGI application. I have followed the exact docs of https://channels.readthedocs.io/en/latest/deploying.html But when I am checking my logs i am ending up with: CRITICAL Listen failure: Couldn't listen on 0.0.0.0:x: [Errno 98] Address already in use. I have tried changing ports but at last, ending up with the same: Eg: for port 8005 daphne -p 8005 -b 0.0.0.0 myproject.asgi:application I am ending up with: Configuring endpoint unix:/run/daphne/daphne1.sock 2020-07-16 08:22:10,324 INFO Starting server at fd:fileno=0, tcp:port=8005:interface=0.0.0.0, unix:/run/daphne/daphne0.sock 2020-07-16 08:22:10,324 INFO HTTP/2 support not enabled (install the http2 and tls Twisted extras) 2020-07-16 08:22:10,325 INFO Configuring endpoint fd:fileno=0 2020-07-16 08:22:10,345 INFO Listening on TCP address 127.0.0.1:8005 2020-07-16 08:22:10,345 INFO Configuring endpoint tcp:port=8005:interface=0.0.0.0 In my asgi.log file. I am using the exact config /etc/supervisor/conf.d/abc.conf and my /etc/nginx/sites-enabled/isbuddy as: server { listen 80 default_server; listen [::]:80 default_server; location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_pass http://0.0.0.0:8005; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } I tried all the possibilities available by checking every docs. I want my website to run in my public IP. -
Django Ajax Multiple File Forms Redirecting to Json
Everytime I submit the form, Django redirects me to a new page with the json data instead of staying on the current page. Confused as to what is wrong. I am using Bootstrap and also had problems with inmemoryuploadedfiles that I was trying to serialize but not completely sure if that is the problem here. Any help would be great. Thanks! Scripts <script type="text/javascript"> var frm = $('#uploadForm'); frm.submit(function () { $.ajax({ type: frm.attr('method'), url: '{% url "replay-upload" %}', data: frm.serialize(), success: function (data) { console.log("Success: " + data) $("#dangerAlert").style.visibility = "hidden"; $("#successAlert").style.visibility = "visible"; }, error: function (data) { console.log("Failed: " + data) $("#successAlert").style.visibility = "hidden"; $("#dangerAlert").style.visibility = "visible"; } }); return false; }); </script> HTML <form id="uploadForm" action='.' method='post' enctype="multipart/form-data"> {% csrf_token %} <div class="form-group font-weight-bold h5"> {{ form.replay_file | as_crispy_field }} <!--<label class="custom-file-label" for="customFile">Choose Replay File...</label>--> </div> <input type="submit" class="btn btn-outline-primary" value="Upload"> </form> <div id="successAlert" class="alert alert-success" style="visibility: hidden"> <strong>Success!</strong> You uploaded your replays </div> <div id="dangerAlert" class="alert alert-danger" style="visibility:hidden;"> <strong>Danger!</strong> Your upload failed. Please check that you uploaded a proper replay </div> Views.py class FileFieldView(FormView): form_class = FileFieldForm template_name = 'PlayerMatch/replay_file_upload.html' def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('replay_file') requestFiles … -
Back button on browser doesn't refresh content/send requests for new data
I have a React frontend Django backend app which is basically like a feed (ex: Instagram, Facebook). When the user loads the feed, a request is sent to my backend API which will return the information for the posts displayed on the feed. When the user clicks on a post, they are directed to a separate page showing only that post; this separate page makes a request to my backend API which returns the information for that post only. There is a "like" button for each post (ex: heart for Instagram posts), which sends a request to my backend API to add the post to the user's list of liked posts. If a user clicks "like", the heart should be filled in. After the following steps: user goes to the feed user clicks on a post and is taken to a page with only that post user clicks "like" user clicks back button in the browser to go back to the feed I want the post to show that it has been liked. However, since the back button doesn't send new requests to my backend API to get the data for the feed, the post doesn't show that it's been … -
Differences between frameworks and things like AJAX/Django e.c.t?
I've recently been looking into doing some more backend work but am completely overwhelmed by the amount of different ways to go about things. I've read about React, Vue and Node JS and know that they're frameworks for Javascript (still don't entirely understand what a framework really is). I've also read about Django which is used for a Python backend, but then also things like AJAX which interacts with JavaScript. Where does PHP come into everything and how does one decide what to use/what all the differences are. Apologies if this isn't the right place to ask, but any resources would be greatly appreciated! -
Can't call model to Django template
I'm trying to call an attribute from my model into my HTML template using Django. There is something strange going on as I am only able to call one of my two models into the template. Both models are working perfectly fine as far as I can tell by looking into my database. This is what my models.py looks like class Respondez(models.Model): responder = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='scores') score = models.IntegerField(default=0) post_time = models.DateTimeField(default=timezone.now) class Meta: ordering = ['post_time'] def __str__(self): return self.score class Profilez(models.Model): newuser = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True,null=True) preference = models.CharField(max_length=30) def __str__(self): return self.newuser I am trying to call Profilez. However, only Respondez can be called. This is the view I'm calling from, which I simplified. @login_required def add(request): p = Profilez() z = Respondez() context = { 'p' : p, 'z' : z } return render(request, 'rating/add.html', context) To test whether I can call my models, I have simple header tags in HTML for my template, add.html: {% extends "rating/base.html" %} {% block content%} <h3> {{user.username}} </h3> <h3> {{ z.post_time }}</h3> <h3>{{ p.newuser }}</h3> No matter which attribute I call from the models, the line for Respondez works but nothing works for my Profilez model. This is … -
How to remove Key duplication error Django?
Stack PostgresQL 9.3 on Ubuntu 18.04 Django 3.0 with DRF Problem I am trying to build a model with the below desired models.py. But I used the pythonic way to name variables, but I now realize that PostgreSQL ignores the "_", thus "region" and "region_number" appear to be the same key. region_number should be regionNumber My question is how to I correct this? What I have tried: Simply correcting the model element names and migrating - error is still there Migrating back to before I applied this migration Dropping the Index in SQL; returns "cannot drop index XXX_Index because constraint XXX_Index on table (my_table_name) requires it CURRENT models.py from django.db import models class DataInput(models.Model): name = models.CharField(max_length=45) country = models.CharField(max_length=55) region = models.CharField(max_length=55) region_number = models.IntegerField() Error python manage.py migrate psycopg2.errors.UniqueViolation: could not create unique index "Region and Number" DETAIL: Key (region, region_number)=(US EAST, 1) is duplicated. DESIRED models.py from django.db import models class DataInput(models.Model): name = models.CharField(max_length=45) country = models.CharField(max_length=55) region = models.CharField(max_length=55) regionNumber = models.IntegerField() Thanks so much! -
How to have a follow/unfollow on a user's posts
I have been trying make users follow other users from thier posts like in instagrams explore page. Currently a user can just follow and unfollow other users from their profile but I will like to have that follow/unfollow on their posts too. I tried to make this happen but in the process I got a NameError name 'username' is not defined, How can I fix this error in order to make this work? models.py (mates model is where the follow/unfollow should go) class Mates(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='usermates', unique=True) req_bio = models.CharField(max_length=400) class Following(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) followed = models.ManyToManyField(User, related_name="followed") follower = models.ManyToManyField(User, related_name="follower") @classmethod def follow(cls, user, another_account): obj, create = cls.objects.get_or_create(user = user) obj.followed.add(another_account) print("followed") @classmethod def unfollow(cls, user, another_account): obj, create = cls.objects.get_or_create(user = user) obj.followed.remove(another_account) print("unfollowed") def __str__(self): return f'{self.user.username} Profile' class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png') bio = models.CharField(max_length=400, default=1, null=True) connection = models.CharField(max_length = 100, blank=True) follower = models.IntegerField(default=0) following = models.IntegerField(default=0) def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.profile_pic.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.profile_pic.path) def __str__(self): return f'{self.user.username} Profile' views.py def matesmain(request): if request.user.has_posts(): contents … -
ImproperlyConfigured at /project/ PostListView is missing a QuerySet. Define PostListView.model,
I wanted to list all the projects for gitlab in my template django but it doesn't work , this is my code in the page views views.py class PostListView(ListView): template_name = 'blog/home.html' ordering = ['-date_posted'] def get_table(self, form, request): headers = { 'content-type':'application/json', 'PRIVATE-TOKEN': ''} headers = {'Content-type': 'application/json', 'PRIVATE-TOKEN': '','Authorization': 'Basic =='} fields=form.cleaned_data['Project_name'] fiel=form.cleaned_data['project_description'] level=form.cleaned_data['visibility_Level'] name=form.cleaned_data['author'] date=form.cleaned_data['date_posted'] iden=form.cleaned_data['Identifiat'] url = "http://172.16.0.111/api/v4/projects/" url2="http://172.16.0.112:3000/projects.json" data ={"name": fields, "description":fiel,"created_at":date} datar= '{"project" :{"name" :"'+fields+'","identifier" : "'+iden+'" ,"description":"'+fiel+'"}}' data=JsonResponse(data) response = requests.get(url,headers=headers, data=data) response = requests.get( url2, headers=headers, data=datar) response.json() return response print(response.text.encode('utf8')) home.html {% for post in posts %} <tr> <td>{{ post.id }} </td> <td>{{ post.Project_name }}</td> <td>{{ post.Identifiat}}</td> <td>{{ post.project_description }}</td> <td>{{ post.visibility_Level }}</td> <td>{{ post.name_customer}}</td> </tr> {endfor} -
How do I use .env in Django?
My goal is to email using Python Django without having my email password being shown in the actual code. After some research, I guess I can store my password in an .env file and then access the password from the .env file. So, I currently have an .env file in my Django project with this line of code: export EMAIL_HOST = 'smtp.gmail.com' And in my settings.py, I have these: import environ env = environ.Env() environ.Env.read_env() EMAIL_HOST = os.environ.get('EMAIL_HOST') print(EMAIL_HOST) But the printed result is None. print(os.environ) spits out something though. How can I get my .env file to work? -
Are new_or_get and get_or_create the same?
Here is my code. views.py cart_obj, cart_created = Cart.objects.new_or_get(request) models.py def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.get_queryset().filter(id=cart_id) if qs.count() == 1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj.user = request.user cart_obj.save() else: cart_obj = Cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj I wanted to understand what cart_obj, cart_created meant. I Googled it and found the below. Any keyword arguments passed to get_or_create() — except an optional one called defaults — will be used in a get() call. If an object is found, get_or_create() returns a tuple of that object and False. If multiple objects are found, get_or_create raises MultipleObjectsReturned. If an object is not found, get_or_create() will instantiate and save a new object, returning a tuple of the new object and True. The new object will be created roughly according to this algorithm: I thought the above description described what was happening in my code (or at least described something quite similar to what my code was doing). But in my code I use new_or_get whereas the above description relates to get_or_create. I added two print statements to my code so I could get better understand it. cart_obj, … -
My django template does not seem to refresh itself when I add/update values
I've created a usecase.py file to conduct basic calculations... the simple logic in that file is: for date in mydate: if date == now: print("Date is the present") elif date > now: print("Date is the future") elif date < now: print("Date is the past") else: print("Error") The first time I pass this from my usecase.py into views.py, and then into the template, everything seems to work correctly. When I update the mydate value however, the update does not render onto my template, and it continues to render a previous value. If instead of putting the logic into a separate usecase.py file I put it directly into the appropriate view, it seems to work fine again there. Wondering why this is happening and if it is bad practice to put logic in a view. Though this example is somewhat simplistic, the logic builds on it and gets a little more complex. Thanks! -
Django Form & Bootstrap Select
I am trying to add additional fields to a Django form using Bootstrap select. I currently have these two models: class Organisation(models.Model): title = models.CharField() topic = models.ForeignKey(Topic) pic = models.ImageField() Class Choice organisation = models.ForeignKey(Organisation, on_delete=models.CASCADE) and a form containing this widget: widgets = { 'organisation': forms.Select(attrs={'class': 'form-control selectpicker', 'data-live-search':'true'}), }, This is working correctly and is rendering the drop down select form on the template. However, I also want to show the image and topic like so: <option data-thumbnail="Organisation.pic" data subtext="Organisation.topic">Organisation.title</option> or alternatively, display results grouped by topic: <optgroup label="Topic1"> <option data-thumbnail="Organisation.pic"> Organisation.title</option> <option data-thumbnail="Organisation2.pic"> Organisation2.title</option> </optgroup> <optgroup label="Topic2"> <option data-thumbnail="Organisation3.pic"> Organisation3.title</option> </optgroup> I've tried to do this directly in the template using a for loop for each option (i.e for x, org in form.fields.organisation.choices), however it doesn't pull in any other fields beyond the organisation title (organisation.topic and organisation.pic.url, don't seem to work)? -
What these curly braces mean in python Django? *{}*
I was working on some code refactoring and i encountered these bad guys. What is their porpouse? Looks like a formatter but im not pretty sure. if data: result = '' for recipe_data in data: url = recipe_data['url'] name = recipe_data['name'] rating = recipe_data['rating'] rating_count = recipe_data['ratingcount'] prep = recipe_data['prep'] cook = recipe_data['cook'] ready_in = recipe_data['ready in'] calories = recipe_data['calories'] result += """ {} {} calories Thanks.