Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.2 - how can i made redirect with context?
The main page is block with random instance of model. Also there is a page with form for add new instance . After create new instance i want redirect to main page, but it must render not random instance, it must render instance, which i create. How can i make this? main page controller: def brick_page_foo(request): peekeys = [] for item in Brick.objects.filter(is_published=True): peekeys.append(item.pk) brick = Brick.objects.get(id=random.choice(peekeys)) if brick.image: image_flag = image_flag_foo(brick.image) else: image_flag = 'no_image' context = {'brick':brick, 'image_flag':image_flag,} return render(request, 'brick/bricks.html', context) add form controller: def add_brick(request): if request.method == 'POST': form = BrickAddForm(request.POST, request.FILES) if form.is_valid(): brick = form.save() print(colored(brick, 'yellow')) if brick.image: image_flag = image_flag_foo(brick.image) else: image_flag = 'no_image' context = {'brick':brick, 'image_flag':image_flag,} return render(request, 'brick/bricks.html', context) else: form = BrickAddForm() return render(request, 'brick/add_brick.html', {'form':form}) -
Possible source of cascade deletion on Django 1.9 project?
I'm working on a Django 1.9 project with a huge source and lots of is inherited from previous developers. When I delete a User object from the shell there are many other related objects that get deleted as well. I get a print output with a Tuple containing: (# of deleted objects, {u'CLASS_NAME': #number of deleted objects...}) I've searched all the code throughly and there are no Signals attached to User pre_ post_ or on_ delete, neither I can find where this print output is constructed... so, I have no idea where this is coming from. Any ideas for other possible ways this can be happening? -
changing 'DEFAULT_FILE_STORAGE' causing high TTFB ( waiting time ) with boto3
My settings ... AWS_ACCESS_KEY_ID = 'MY_KEY' AWS_SECRET_ACCESS_KEY = 'MY_SECRET_KEY' AWS_STORAGE_BUCKET_NAME = 'wallpapers' AWS_S3_ENDPOINT_URL = 'https://sgp1.digitaloceanspaces.com' AWS_S3_CUSTOM_DOMAIN = 'wallpapers.sgp1.cdn.digitaloceanspaces.com' AWS_QUERYSTRING_AUTH = False AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = 'public-read' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, 'media') MEDIA_ROOT = 'media/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' ... when I open 'http://127.0.0.1:8000/' this causes high TTFB... but when I comment out/ remove this in settings.py... #DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' then everything works fine -
plt.close() or plt.clf() doesnt effect on image
I save my image with plt.savefig(). But after that plt.close() doesnt work and it shows the previous pics as well. Could you please indicate the error, please. I cant avoid the error "networkx.exception.NodeNotFound: source node KAZ/TNS/Алматы not in graph" in nx.all_simple_paths(g, source=point1.point, target=point2.point), if the both points are not in graph. Here is my views.py point1 = get_object_or_404(Point, pk=pk1) point2 = get_object_or_404(Point, pk=pk2) g = nx.Graph() g2 = nx.Graph() data = [] content = {'name':None, 'points': None, 'sum_line':0, "sum_cable": 0} for form in Form61KLS.objects.all(): g.add_edge(form.point1.point, form.point2.point, weight=form.total_length_line) g2.add_edge(form.point1.point, form.point2.point, weight=form.total_length_cable) g.add_node(form.point1.point, pos=(1, 20)) g.add_node(form.point2.point, pos=(1, 20)) path = [] for p in nx.all_simple_paths(g, source=point1.point, target=point2.point): path.append(p) for p in path: path_length = nx.path_weight(g, p, weight='weight') path_length1 = nx.path_weight(g2, p, weight='weight') finish_total = copy.deepcopy(content) finish_total['name'] = "Варианты:" finish_total['points'] = p finish_total['sum_line'] = path_length finish_total['sum_cable'] = path_length1 data.append(finish_total) for p in nx.all_simple_edge_paths(g, source=point1.point, target=point2.point): for t in p: total = copy.deepcopy(content) total['name'] = "Разбивка:" total['points'] = t path_length = nx.path_weight(g, t, weight='weight') path_length1 = nx.path_weight(g2, t, weight='weight') total['sum_line'] = path_length total['sum_cable'] = path_length1 data.append(total) pos = nx.spring_layout(g) labels = nx.get_edge_attributes(g, 'weight') nx.draw_networkx_edge_labels(g, pos, edge_labels=labels, font_size=8, font_color='blue', font_family='sans-serif', font_weight='normal', horizontalalignment='center', verticalalignment='center') nx.draw(g, pos=pos, node_size=250, node_color='blue', linewidths=1, font_size=7, font_family='sans-serif', edge_color='y', with_labels=True) if os.path.exists(BASE_DIR + … -
Delete from django database with many form in same template
I am new to django and I'm trying to build a to do list so what I click on "✓" button it turn the item to green from red using javascript and now Iam trying to make the button "X" delete objects from the django database so I stuck here this is my code I am waiting for your help my views from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from .forms import * # Create your views here. def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == "POST" : form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect("/") context = { 'tasks' : tasks , 'form' : form } return render(request,"tasks/list.html", context) def deletetask(request, pk): if request.method == "POST" and "delete" in request.POST: print(request.POST) print("good work") item = request.POST.get(id=pk) Task.objects.delete(id=item) return render(request,"tasks/list.html") my forms.py from django import forms from django.forms import ModelForm from .models import * class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' my models.py from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) creted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title my template <h3>Hello world from templates</h3> <form action="/" method="POST"> {% csrf_token … -
How can I parse and show sequence charts and flow charts of markdown content on html?
I'm developing a blog app by using django, there's a feature is that showing articles written by markdown. Now I have been able to successfully parse some markdown syntax, but I can't do it well on sequence charts and flow charts. Are there some modules can do it well? Thank for your answer firstly!! -
Django/Python feeding back ImproperlyConfigured for makemigrations for AppConfiguring
Following along a tutorial and I have been able to solve all my little issues so far until I get to my back-end creating my own 'app' for data I can lookup with SQlite. My work flow: > DJANGO-WEBSITE: > capstone_project_website: > settings.py > apps: > accounts: > models.py > apps.py > requirements: > scripts: > manage.py my /mymodels.py: from django.db import models from django.contrib.auth.models import User class UserInterest(models.Model): # name of interest name = models.CharField(max_length=64, unique=True) normalized_name = models.CharField(max_length=64, unique=True) # string function to print the name def __str__(self): return self.name class UserPersona(models.Model): name = models.CharField(max_length=64, unique=True) normalized_name = models.CharField(max_length=64, unique=True) description = models.CharField(max_length=200) def __str__(self): return self.name # Create your models here class UserProfile(models.Model): # Owner. Foreign key. Whenever we fetch user, we should fetch the user profile # related_name = we can access profile through user object aka request.user.profile user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile") # settings is_full_name_displayed = models.BooleanField(default=True) # details bio = models.CharField(max_length=500, default=True, null=True) website = models.URLField(max_length=500, default=True, null=True) persona = models.ForeignKey(UserPersona, on_delete=models.SET_NULL, blank=True, null=True) interests = models.ManyToManyField(UserInterest, blank=True) my /settings.py: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "capstone_project_website.apps.accounts", ] my /apps.py from django.apps import AppConfig class AccountsConfig(AppConfig): name = "accounts" the error … -
Can I add Django context as prerendered text in input field?
Let's say we have: <input type="text" value="{{ title }}" /> This obviously doesn't work. Can I get context to be shown as prerendered text in input field, providing the fact that I have stored the text in another language somewhere else, and I converted it in html language in views.py and gave it a context? -
Processes in Python 3.9 exiting with code 1 when use Postgres
I have a piece of code that generates an Insert SQL query and executes it using Django cursor. This works correctly with Python 3.8 but I've updated my Ubuntu which cames with Python 3.9 and now It's always exiting with code 1. def __save_result_in_db(self, combinations: List[CorResult], experiment: Experiment, table_name: str): insert_query_prefix = f'INSERT INTO {table_name} ... VALUES ' insert_template = "('{}','{}',..." + str(experiment.pk) + ")" for chunk in self.get_chunks_of_list(...): insert_statements: List[str] = [ insert_template.format( # SOME fields ) for cor_result in chunk ] insert_query = insert_query_prefix + ','.join(insert_statements) with connection.cursor() as cursor: cursor.execute(insert_query) logging.warning(f'THIS MESSAGE IS PRINTED!') # Calling p = Process(target=self.__save_result_in_db, args=(result_combinations, experiment, table_name)) p.start() p.join() if p.exitcode != 0: logging.error(f'Process for experiment with id = {experiment.pk} has exit with code {p.exitcode}') # Always is 1 raise ExperimentFailed Even putting an explicit exit(0) at the end of __save_result_in_db doesn't prevent to the process to exit with code 1. Is there I'm missing? Any kind of help would be really appreciated -
python django why the form is not showing in the html page?
** for some reason my form is not showing in the template can someone tell me why , think you. ** views.py i think the problem is here but i cant find it i followed the documentation and got nothing also def contact(request): print(request.POST) forms=contactform(request.POST or None) if forms.is_valid(): print(forms.cleaned_data()) context= { "title":"contact", "form": forms } return render(request,"form.html",context) ``` > forms.py ``` from django import forms class contactform(forms.ModelForm): full_name=forms.CharField() email=forms.EmailField() text=forms.CharField(widget=forms.Textarea) ``` > form.html ``` {% extends "gta.html" %} {% block ferr%} {% if title %} <h1>{{title}}</h1> {% endif %} <form method="POST" action="."> {% csrf_token %} {{forms.as_p}} <button type="submit">submitt</button> </form> {% endblock %} -
Can I return a different Django Response based on whether or not the view is invoked from swagger?
I am using Django-Rest-Framework for my API. And I am documenting that API w/ swagger using drf_yasg. One of my views returns a Django FileResponse. When I access the view directly at "http://localhost:8000/api/my_documents/1" it successfully displays the (PDF) file. But when I access it via swagger it successfully returns a 200 but gives the following message: Unrecognized response type; displaying content as text. This is b/c of this issue in swagger itself. As suggested in that ticket, the problem goes away if I change the "Content-Disposition" response header from "inline" to "attachment". However, I don't want to always download the file. My question is: Can I determine whether the request was made by swagger in the view and conditionally change the headers? Something like: class MyDocumentView(GenericAPIVIew): def get(self, request, pk): my_document = MyDocument.objects.get(pk=pk) response = FileResponse(my_document.file) # (file is a FileField) # WHAT DO I PUT HERE ?!? if request.is_from_swagger: response.headers["Content-Disposition"] = response.headers["Content-Disposition"].replace("inline", "attachment") return response Thanks. -
Why does Django require change permission to add a foreign key?
I have two models in my application, Product and Holder. A Holder can have n products, and a Product must have one Holder. These are the classes: class Product: title = models.CharField(verbose_name=_('Title'), max_length=100) holder = models.ForeignKey(verbose_name=_('Main Holder'), to=Holder, on_delete=models.PROTECT) ... class Holder: name = models.CharField(verbose_name=_('Name'), max_length=50, unique=True) ... When a user that is a staff_member tries to create or change a Product, that specific user has to have the database's change_holder permission assigned to them, otherwise they can't assign a Holder to that Product. The list of holders won't even load up on the respective field on Admin, as the following image illustrates. Anyway, what I'd like to know is what justifies this behavior. Why would a user need permission to change the foreign key model, if they're not changing that model, but the one that contains the key? -
How can i implement a function to any user add products to my site(Django)?
I am trying to insert my product by category, and the product attributs in django. I have two model Product(Tool) and Category. If i'm logged has user i want to add my product in my site. This is my product models from django.db import models from django.urls import reverse from model_utils.models import TimeStampedModel from utool import settings class AvailableManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_available=True) class Category(TimeStampedModel): name = models.CharField(max_length=255, unique=True) slug = AutoSlugField(unique=True, always_update=False, populate_from="name") class Meta: ordering = ("name",) verbose_name = "category" verbose_name_plural = "categories" def __str__(self): return self.name def get_absolute_url(self): return reverse("pages:list_by_category", kwargs={"slug": self.slug}) class Tool(TimeStampedModel): category = models.ForeignKey( Category, related_name="tools", on_delete=models.CASCADE ) name = models.CharField(max_length=255) slug = AutoSlugField(unique=True, always_update=False, populate_from="name") image = models.ImageField(upload_to="tools/%Y/%m/%d", blank=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) is_available = models.BooleanField(default=True) # user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) objects = models.Manager() available = AvailableManager() class Meta: ordering = ("name",) def __str__(self): return self.name def get_absolute_url(self): return reverse("pages:detail", kwargs={"slug": self.slug}) And this is my product views from django.views.generic import DetailView, ListView from .models import Category, Tool class ToolDetailView(DetailView): queryset = Tool.available.all() class ToolListView(ListView): category = None paginate_by = 6 def get_queryset(self): queryset = Tool.available.all() category_slug = self.kwargs.get("slug") if category_slug: self.category = get_object_or_404(Category, slug=category_slug) queryset = queryset.filter(category=self.category) return queryset … -
'SalaryAdmin' object has no attribute 'request'
Hello I want to add method to list display in django admin but am getting error say SalryAdmin has no attribute request here my admin @admin.register(Salary) class SalaryAdmin(admin.ModelAdmin): list_display = ['user_name', 'action'] def action(self, obj): if not self.request.user.is_superuser: if obj.hr_state == 'request-change-approved' and self.request.user.user_role.position.code == 'HRM': return True else: return False else: return True any help appreciated -
Using ckeditor in Django without the built-in provided forms
I am new to Django and till now, I have not been using Django forms. Instead, I have been making my own customised forms in templates by using Bootstrap and css. But, now, I have a field where I want to use a rich text editor like Ckeditor. Is there a way to use it without the Django built-in forms? Thank youuu for your reply :)) -
use of upload_to function when creating on object in django
here is my model in django : import os def upload_location_buy(instance, filename): ext = filename.split('.')[-1] filename = '%s.%s' % (instance.name+"_"+str(random.randint(1000, 9999)), ext) print(os.path.join('uploads', filename)) return os.path.join('uploads', filename) class Buy(models.Model): pic_front = models.ImageField(blank=True, upload_to=upload_location_buy,default='') When i try : b = Buy(pic_front="appartement_a.jpg") b.save() it does nothing exception linking the current pic in the current path, so not using the function in the model. And when i do : b = Buy(pic_front=upload_location_buy("appartement_a.jpg")) b.save() it give me an error because it seems to need the instance. TypeError: upload_location_buy() missing 1 required positional argument: 'filename' How to create a buy object, giving it a picture and using the upload_location_buy whend doing it without the admin ? When i upload a pic in the admin it works. how to give it the instance name or do it correctly ? regards -
I am getting an error no such table: users_profile. Why so?
I have the following Profile model as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.png', upload_to='profile_pics') slug = AutoSlugField(populate_from='user') bio = models.CharField(max_length=255, blank=True) friends = models.ManyToManyField("Profile", blank=True) def __str__(self): return str(self.user.username) def get_absolute_url(self): return "/users/{}".format(self.slug) path('users/', users_list, name='users_list'), @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) my_friends = request.user.profile.friends.all() sent_to = [] friends = [] for user in my_friends: friend = user.friends.all() for f in friend: if f in friends: friend = friend.exclude(user=f.user) friends += friend for i in my_friends: if i in friends: friends.remove(i) if request.user.profile in friends: friends.remove(request.user.profile) random_list = random.sample(list(users), min(len(list(users)), 10)) for r in random_list: if r in friends: random_list.remove(r) friends += random_list for i in my_friends: if i in friends: friends.remove(i) for se in sent_friend_requests: sent_to.append(se.to_user) context = { 'users': friends, 'sent': sent_to } return render(request, "users/users_list.html", context) and I have users_list.html template. I have tried building the database tables with migrate command and tables have been created. But I still get the error message: no such table: users_profile What could be the problem? -
Adding item to cart in Python, Django. FieldError at /add/1 -> Cannot resolve keyword 'book' into field. Choices are: author,
I have two functions, one adds items to the cart and one removes. While I try to add the item to the cart I get an error: FieldError at /add/1 Cannot resolve keyword 'book' into field. Choices are: author, author_id, bookorder, description, id, price, publish_date, review, stock, title Where do I go wrong? Any help is appreciated! models.py from django.db.models.query import prefetch_related_objects from django.utils import timezone from django.contrib.auth.models import User class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) def __str__(self): return "%s, %s" % (self.last_name, self.first_name) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, blank=True) description = models.TextField() publish_date = models.DateField(default=timezone.now) price = models.DecimalField(decimal_places=2, max_digits=8) stock = models.IntegerField(default=2) class Meta: verbose_name ='Book' verbose_name_plural = 'Books' db_table = 'book' class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(default=True) order_date = models.DateField(null=True) payment_type = models.CharField(max_length=100, null=True) payment_id = models.CharField(max_length=100, null=True) def add_to_cart(self, book_id): book = Book.objects.get(pk=book_id) try: preexisting_order = Book.objects.get(book=book, cart=self) preexisting_order.quantity += 1 preexisting_order.save() except BookOrder.DoesNotExist: new_order = BookOrder.objects.create( book=book, cart=self, quantity = 1 ) new_order.save def remove_from_cart(self, book_id): book = Book.objects.get(pk=book_id) try: preexisting_order = BookOrder.objects.get(book=book, cart=self) if preexisting_order.quantity > 1: preexisting_order.quantity -= 1 preexisting_order.save() else: preexisting_order.delete() except BookOrder.DoesNotExist: pass class BookOrder(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, … -
CSRF exempt for contactform - Django
Is it safe to use a CSRF exempt for a contactform or a form using the send_mail function from Django? So according to the docs; The first defense against CSRF attacks is to ensure that GET requests (and other ‘safe’ methods, as defined by RFC 7231#section-4.2.1) are side effect free. Is a POST request, which only creates an email message and does not touch the database, considered as a "safe" method? Example code from django.core.mail import BadHeaderError, send_mail from django.http import HttpResponse, HttpResponseRedirect def send_email(request): subject = request.POST.get('subject', '') message = request.POST.get('message', '') from_email = request.POST.get('from_email', '') if subject and message and from_email: try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: # In reality we'd use a form class # to get proper validation errors. return HttpResponse('Make sure all fields are entered and valid.') *example from docs I'm just wondering if I'm not missing something before I add the CSRF exempt. Now I hear you thinking, why would someone want to disable the CSRF validation? In the EU we have to comply to the GDPR. By setting a cookie, we need to explicitly ask the user to accept cookies, if we can prevent setting … -
Emailing a PDF Generated from HTML: expected bytes-like object, not HttpResponse
I am trying to email a PDF that has been generated from a HTML template. I get the following error: expected bytes-like object, not HttpResponse generate_pdf: def generate_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None view for pdf emailing: def pdfView(request): data = {'test':'test', 'mylist': 'test' } pdf = generate_pdf('main/test.html', data) msg = EmailMessage("title", "content", to=["email@email.com"]) msg.attach('my_pdf.pdf', pdf, 'application/pdf') msg.content_subtype = "html" msg.send() return HttpResponse(pdf, content_type='application/pdf') -
Save image from Django to S3 AWS without admin.py
I'm in a face recognition project and I would like that the final result show the image that the person upload (His/Her face) and the image of a person that you look a like. I want to store the uploaded image by some user to my S3 AWS bucket but I'm not using the admin.py script because I created a new template: where you upload your pic and then the "Ir" button runs a python function called "fibocal". template.html <div class="container-contact100-form-btn" id = "hola"> <ul><button type="submit" class="notify-btn" onclick="showLoaderOnClick('{% url 'gallery:fibocal' %}')"> <span> Ir </span> </button></ul> </div> and the "fibocal" function is in views.py: def fibocal(request): if request.method == 'POST': img_loaded = request.FILES['image'] imagenes = FR(img_loaded) return render(request, 'base.html', {'name': imagenes[0], 'prct':imagenes[1], 'imagen': imagenes[2]}) else: return render(request, 'home/register.html', {}) So, I would like that when the user upload the image it will be save to the S3 budget, but I don´t know how to add the "Save" button that is in the default admin template by default. I would like to add a new function to "Ir" button that save the image at the S3 AWS and also runs the fibocal function. Thanks! -
How to make reverse foregnkey/1to1/MtoM connections explicit in django models?
Say there are two models like these: class Post(models.Model): ... class User(models.Model): posts = ManyToManyField(post, ...) ... I know that Post.user is still available in the django querysets and I know about relatedname but there are cases where I also need to add field users to Post model, to which, if I remember correcly, django issues a warning. In my case, I need to write a serializer (project uses DRF) for such implicit field, which is not possible (because "model Post doesn't have field users" to continue the example). And even if it's ok to ignore warning and just make fields explicit, situation is still hard since MtoM is an reverse of MtoM and 1to1 is a reverse of 1to1 but there is no reverse to foreignKey. -
how can restrict access to media image url
how can restrict access to media image url , and make it accessible only by access owner user in django , here is my class model : class private_image(models.Model): i_user = models.OneToOneField(User, related_name='related_PRF_user', on_delete=models.CASCADE) i_image= models.ImageField(upload_to='images', blank=True, null=True ) and my media settings is : MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root/') MEDIA_URL = '/media_url/' i believe, i can make a small function to check access-user and requested URL '/media_url/images/' to get image name , and then get an object from database using image name and then check the owner(i_user) if same access-user . but how can i tell Django to use this function before service MEDIA_URL requests . if you have an example , that will be very helpful . thank you in advanced -
Django and Vuetify
Good morning, good afternoon or good night. How are you? I'm implementing an application using the famous and our Python friend Django and inside it I'm using Vuetify with our VueJs. I always used this using and creating APIs in Django and consuming it on Vuetify. However, I was given the challenge of using Vuetify inside Django using its CDN, but I have a lot of difficulties and I wanted to know if anyone here on the stack has been there. (In case of doubt, not that of npm install inside the django project, but just consume and call the components .Vue like this using your cdn too) In the base.html of django I was able to redenrize a vue page <!DOCTYPE html> {% load static %} <!--{% url 'social:begin' 'google-oauth2' as url_login_gmail %}--> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title>Odontotolgia Undb</title> <link rel="shortcut icon" href="https://www.undb.edu.br/hubfs/avatar_site.png"> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Material+Icons" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/@mdi/font@4.x/css/materialdesignicons.min.css" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, minimal-ui"> <style type="text/css"> a{ color: #fff; text-decoration: none; text-decoration-line: none; text-decoration-style: initial; text-decoration-color: initial; } </style> </head> <body> <div id="app"> <v-card height="665px" > <v-navigation-drawer v-model="drawer" :mini-variant.sync="mini" permanent absolute > <v-list-item class="px-4"> <v-list-item-avatar> <v-img src="https://randomuser.me/api/portraits/men/85.jpg"></v-img> </v-list-item-avatar> <v-list-item-title> &nbsp; … -
Why is Django not pulling from session? Also .get funtion no longer lights up as the .all function does? Nothing displays from database
`from django.shortcuts import render,redirect, HttpResponse` `from user_login_app.models import User` `from .models import Book,Author,Rating` `from django.contrib import messages` def index(request): `user=User.objects.get(id=request.session['user_id'])`===================================================On this line the get function isn't operating I can no longer pull from session and the function doesn't light up the way it did. I also get no user display on the page. Normally the .get function highlights as the .all function does, also displays the logged in user on the page. No I get nothing from Session. To be clear, I also made all migrations. I have items in my database. I just can't pull them out. As I have in the past. `author=Author.objects.all()` `rating=Rating.objects.all()`My context statment no longer renders anything. I double checked it agianst past projects. those were all written very similarly. `context={` `'users':user,` `' authors':author,` `'ratings':rating,` } return render(request,'book_home.html',context) I don't get why my .get function doesn't work?? I hope someone has an answer to this puzzle.