Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I pass a js var to a django view
It's my first time working with JS, and I don't know how to pass a selected row in a table to my django's view file. This is my HTML and my JS: var tabela = document.getElementById("minhaTabela"); var linhas = tabela.getElementsByTagName("tr"); for(var i = 0; i < linhas.length; i++){ var linha = linhas[i]; linha.addEventListener("click", function(){ selLinha(this, true); }); } function selLinha(linha, multiplos){ if(!multiplos){ var linhas = linha.parentElement.getElementsByTagName("tr"); for(var i = 0; i < linhas.length; i++){ var linha_ = linhas[i]; linha_.classList.remove("selecionado"); } } linha.classList.toggle("selecionado"); } var btnVisualizar = document.getElementById("visualizarDados"); btnVisualizar.addEventListener("click", function(){ var selecionados = tabela.getElementsByClassName("selecionado"); //Verificar se eestá selecionado if(selecionados.length < 1){ alert("Selecione pelo menos uma linha"); return false; } var dados = ""; for(var i = 0; i < selecionados.length; i++){ var selecionado = selecionados[i]; selecionado = selecionado.getElementsByTagName("td"); dados += "CNPJ: " + selecionado[0].innerHTML + " - RAZÃO SOCIAL: " + selecionado[1].innerHTML + " - NOME FANTASIA: " + selecionado[2].innerHTML + "\n"; } alert(dados); }); {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{% static 'css/banco.css' %}"> </head> <body> <button id="visualizarDados">Visualizar Dados</button> <table border="1" class="dataframe" id="minhaTabela"> <thead> <tr style="text-align: right;"> <th></th> <th>CNPJ</th> <th>RazaoSocial</th> <th>NomeFantasia</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>00000000000</td> <td>xxxxxxxxxxxxx S/A</td> <td>xxxxxxxxxxx</td> </tr> <tr> … -
how to access a django webapp REST API endpoint from unix without requiring the user to enter credentials
i have a django webapp running at work. we have some REST APIs available which get accessed by our flow in unix. currently to avoid asking the users to enter their credentials, we store a service account name and credentials in a "secret" location on disk. my python code reads credentials from there to login and access the REST API running on our django app. i am sure there is a better way to do this. is there a way to leverage that the user is logged into unix somehow to get authentication to work with the REST API? i heard kerberos might be useful here? thanks for the help! -
NoReverseMatch at / Reverse for 'device_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Need some help here: I've tried and googled a lot and can't find the issue. I'm getting this error when tagging a url on a template: NoReverseMatch at / Reverse for 'device_list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] My URLPattern: url(r'^device/list/$', device_list, name='device_list'), My template call: <li class="device"><a href="{% url 'device_list' %}">List Device</a></li> My reverse definition on the CVB on models: @require_role('admin') def device_list(request): """ DEVICE list view """ header_title, path1, path2 = u'List', u'Mgmt', u'LIst' posts = DEVICE.objects.all() keyword = request.GET.get('keyword', '') if keyword: posts = DEVICE.objects.filter(Q(name__contains=keyword) | Q(comment__contains=keyword)| Q(ip__contains=keyword)| Q(new_ip__contains=keyword)| Q(mgmtname__contains=keyword)| Q(port__contains=keyword)) else: posts = DEVICE.objects.exclude(name='ALL').order_by('id') contact_list, p, contacts, page_range, current_page, show_first, show_end = pages(posts, request) return my_render('jasset/device_list.html', locals(), request) -
I must install django for every single project i make?
i am new to Python programming language and Django. I am learning about web development with Django, however, each time I create a new project in PyCharm, it doesn´t recognize django module, so i have to install it again. Is this normal? Because i´ve installed django like 5 times. It doesn´t seem correct to me, there must be a way to install Django once and for all and not have the necessity of using 'pip install django' for each new project I create, I am sure there must be a way but I totally ignore it, I think I have to add django to path but I really don´t know how (just guessing). I will be thankful if anyone can help me :) -
How to make a grid scroll horizontally
I have a grid and I wish I could make it scroll horizontally because currently it is scrolling vertically and I need to have an slider there and firstable to have an slider, it needs to be horizontally scrollable. I think that to make this grid horizontally scrollable the mates-frid-container has to be altered but I dont know how and I have already tried a lot of things overflow and translate, maybe I was doing it wrong. This grid has dynamic data inside so that makes it a bit more complex to make I think. html <div class="mates-grid-content"> <div class="mates-header-content"> </div> <div class="mates-grid-1-1-content"> <div class="mates-grid-2-content"> <button type="button" id="prev-button">prev</button> </div> <div class="mates-grid-1-content"> <div class="mates-item-content"> <img class="mate-pic" src="{{ user.profile.profile_pic.url }}" > </div> <div class="mates-item-content"> <a href="{% url 'profile' username=content.user.username %}" style="float: left">{{ content.user }}</a> </div> <div class="mates-item-content"> <div class="responses"> <div class="response-item-img"> <img class="mates-image" src="{{ content.req_image.url }}" width="400px"> </div> <div class="response-item-bio"> <p>{{ content.req_bio }}</p> </div> <div class="response-item-button"> <button type="submit">Submit</button> </div> </div> </div> </div> <div class="mates-grid-3-content"> <button type="button" id="next-button">next</button> </div> </div> <div class="mates-grid-2-2-content"> </div> </div> css .mates-grid-content { width: 100%; display: grid; grid-template-columns: 1fr; grid-template-rows: 8% 84% 8%; grid-gap: .5rem; } .mates-header-content { display: flex; text-align: center; justify-content: center; align-items: center; grid-column: 1; grid-row: … -
Django navbar not using Bootstrap with no other CSS
I'm creating my navbar right now with Bootstrap and it's not working. I emptied the css file that used to have some navbar-related css and it's not picking anything up. I've tried multiple versions of this and made sure it wasn't a browser issue. Does Django and Bootstrap not work well together without configuration? Both the DjangoGirls and Mozilla tutorials used Bootstrap in the same way so I thought it would be fine. navbar.html <nav class="navbar navbar-expand-sm"> <div class="mx-auto d-sm-flex d-block flex-sm-nowrap"> <div class="collapse navbar-collapse text-center" id="navbarsExample11"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'index' %}">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'bakes' %}">Baking List</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'about' %}">About</a> </li> </ul> </div> </div> </nav> base.html <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Post List</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/food_blog.css' %}"> </head> <body> {% include 'food_blog/navbar.html' %} <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> {% block pagination %} {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="{{ request.path }}?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span … -
Indexing or filtering Wagtail blog posts by MULTIPLE blog tags
I created a basic Wagtail blog page using Wagtail's tutorial. However, now I want to create a filter on the blog page that allows me to index blog pages by MULTIPLE blog tags. Wagtail already comes with Django REST Framework and Django-Taggit. Is there an easy method to creating a filter in models.py and templates using the prepackaged dependencies? If not, what other methods can I use to index Wagtail's blog pages by multiple blog tags? from django.db import models from modelcluster.fields import ParentalKey from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index class BlogIndexPage(Page): intro = RichTextField(blank=True) def get_context(self, request): context = super().get_context(request) blogpages = self.get_children().live().order_by('-first_published_at') context['blogpages'] = blogpages return context class BlogPageTag(TaggedItemBase): content_object = ParentalKey( 'BlogPage', related_name='tagged_items', on_delete=models.CASCADE ) class BlogPage(Page): date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) tags = ClusterTaggableManager(through=BlogPageTag, blank=True) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('intro'), index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), FieldPanel('tags'), ], heading="Blog information"), FieldPanel('intro'), FieldPanel('body'), InlinePanel('gallery_images', label="Gallery images"), ] class BlogTagIndexPage(Page): def get_context(self, … -
Python Django: Filtering data based on custom user model with Foreign Key
i am trying to filter a data set based on a custom user model and having some difficulty with the data. Basically, i have a registration form in which i am making user select the company they are associated with. So i have created a custom user model with a foreign key association to the company table. Now, i am trying to query a second dataset so when user logs in, the application looks up the users company association and filters the data to only show results that are associated to the user's company choice. any suggestion on how i can do this? my user model is below: class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) the table that i am trying to query on has model below: class Order(models.Model): customer = models.ForeignKey(Customer, on_delete= models.SET_NULL, null=True) product = models.ForeignKey(Product, on_delete= models.SET_NULL, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True, blank=True) requestorname = models.CharField(max_length=100, null=True) requestorage = models.CharField(max_length=2,null=True, blank=True) child_id = models.ForeignKey(ChildID, on_delete=models.SET_NULL, null=True, blank=True) comments = models.CharField(max_length=100,null=True, blank=True) requestdate_create = models.DateTimeField(auto_now_add=True) note that both table has association to customer table using a foriegn key, so i want the … -
Adding context to a Class Based View (detail view) geting an error get_context_data() got an unexpected keyword argument 'object'
I am trying to learn how to add a 2nd Context to a Class-Based view which has always been an issue for me and I can't get it right from the first time. In my current project, I am trying to add a comment section to item detail view. I am currently getting an error of get_context_data() got an unexpected keyword argument 'object' which is from the item detail view as I indicated and I don't know who to fix it Here is the item model: class Item(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title here is the comment model: class Comment(models.Model): STATUS = ( ('New', 'New'), ('True', 'True'), ('False', 'False'), ) item = models.ForeignKey(Item, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments") subject = models.CharField(max_length=50, blank=True) comment = models.CharField(max_length=250, blank=True) status = models.CharField(max_length=10, choices=STATUS, default='New') create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '{} by {}'.format(self.subject, str(self.user.username)) class CommentForm(ModelForm): class Meta: model = Comment fields = ['subject', 'comment'] here is the view: class ItemDetailView(DetailView): model = Item template_name = "product.html" def get_context_data(request, id): context = super(ItemDetailView, request).get_context_data() <---------------- error from this line context["comments"] = Comment.objects.filter(item_id=id, status='True') return context here is the add coment view def addcomment(request,id): url = request.META.get('HTTP_REFERER') # get last url … -
How to add call schedule functionality iin django python?
I am new to python. I am developing a website in django framework. I have to add a "scheduling a call" functionality in my website in which the user can book a call (name, email, date and time) and also can see the booked slots in calender. I do not know how to do this nor i am able to find anything like this on the internet. Can anyone here help me for it? -
Does Django caches payload deserialization
Using Django==2.2.13, djangorestframework==3.8.1 I am looking into doing some work in a middleware on incoming requests. A part of the work is to deserialize the payload and check if it has some content (key/value). The Django view is deserializing the payload downstream. I have a few questions: Will Django cache my payload deserialization, or will it do it again in the view regardless? If Django does not cache the deserialized payload, is there any way to enable it to do so? Does the deserialization process take longer when done in the view, vs the middleware? Thank you! -
How to query with the ID of the parent instance using **kwargs?
I am currently implementing soft deletion for all models in my database. The idea is that when an instance gets deleted, it actually gets archived with all of its children. If the user tries to create an instance that is identical to the archived one, the archived one gets undeleted along with all of its children instead of creating a new instance. To do this, I am using django-safedelete where I am making a BaseModel with an overwritten save() method that looks something like this: def save(self, *args, **kwargs): # get the foreign key id foreign_key_id = self.foreign_field.id # execute a query by that id and some other params '''I don't know how to do this''' As to how to do it, I thought I could construct a kwargs dictionary that consists of pairs of <field>:value where <field> = self._meta.get_field(some_field.name) and value = getattr(self, some_field.name). So how do I add the foreign_key_id to kwargs? I know there is this syntax: Model.objects.filter(foreign_field__id=value) ...but I don't know how to replicate that to put into kwargs the way I'm doing it. Likewise, is there a better way to do this in general? I don't want to hard-code too many things, which is why … -
How to query sql on django by user for a model function
In one of my models, I am trying to query the django sql for entries by user to utilize in a function for one of the model objects. How can I successfully query from sql in the biography model to utilize in a function of the journal model for the prompt method object? The below code is what I am trying but doesn't generate any searches for the function: from django.db import models from django.urls import reverse from django.conf import settings import misaka # Create your models here. from django.contrib.auth import get_user_model User = get_user_model() class Biography(models.Model): user = models.ForeignKey(User,related_name='biography',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) prompt = models.CharField(max_length=256,default="") prompt_html = models.CharField(max_length=256,editable=False,default="") entry = models.TextField(default="") entry_html = models.TextField(editable=False) class Journal(models.Model): def gen_prompt(): def sort_by_auth_user(self, item): if item.created_by == self.request.user: return -1 else: return 1 def get_queryset(self): with connection.cursor() as cursor: cursor.execute('SELECT entry FROM journal_Biography') journal_str = cursor.fetchall() sorted_journal_str = sorted(journal_str, key=self.sort_by_auth_user) journal_str = str(sorted_journal_str) qg = TextGenerator(output_type="question") gen_prompt = qg.predict([journal_str]) return gen_prompt user = models.ForeignKey(User,related_name='journal',on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) prompt = models.CharField(max_length=256,default=gen_prompt()) prompt_html = models.CharField(max_length=256,editable=False,default=gen_prompt()) entry = models.TextField(default='') entry_html = models.TextField(editable=False) -
Django error on query set: NotImplementedError: annotate() + distinct(fields) is not implemented
I am trying to write a search functionality for one of my models (Course) however, I am facing an issue when using distinct. raise NotImplementedError('annotate() + distinct(fields) is not implemented.') NotImplementedError: annotate() + distinct(fields) is not implemented. So first if I want to explain what I am trying to achieve, a user will be searching, for instance, a course based on course code, however, they may be two courses with the same level of difficulty in the database, therefore I want to do distinct on the fields so I only see one. def search(self, search_text): search_vectors = ( SearchVector( 'course_code', weight='A', config='english' ) + SearchVector( 'course_instructor', deweight='B', config='english' ) + SearchVector( StringAgg('course_university', delimiter=' '), weight='C', config='english' ) + SearchVector( 'course_code','course_instructor', weight='A', config='english' ) + SearchVector( 'course_university','course_instructor', weight='A', config='english' ) ) search_query = SearchQuery( search_text, config='english' ) search_rank = SearchRank(search_vectors,search_query) trigram = (TrigramSimilarity( 'course_code', search_text ) + TrigramSimilarity( 'course_instructor', search_text ) + TrigramSimilarity( 'course_university', search_text ) ) qs = ( self.get_queryset() .annotate(rank=search_rank, trigram=trigram) .filter( Q(rank__gte=0.2)| Q(trigram__gte=0.09)| Q(course_code__icontains=search_text) ) .order_by('-rank').distinct('course_code','course_instructor','course_university') ) return qs And my model is: class Course(models.Model): class Difficulty(models.TextChoices): EASY = '1', 'Easy' MEDIUM = '2', 'Medium' HARD = '3', 'Hard' FAILED = '4', 'Failed' course_code = models.CharField(max_length=20) course_university = … -
django allow upload file in cpanel shareserver namecheap
I am deploying my django application on a shared namecheap server. I would like to know how I should configure correctly to allow users to upload files. if you have any tutorial or guide. locally I am managing to upload my files by views and by admin. -
How to sorted repostories from Github API by stars forks and size
I'm trying to make an github profile project using python and django and I already pull out the user repos API and I want to sorted it by stars or forks or size and how to display just 8 repos on the webpage. How can I do that? Here is my views.py: def user(req, username): username = str.lower(username) # Get User Info with urlopen(f'https://api.github.com/users/{username}') as response: source = response.read() data = json.loads(source) # Get Limit Call API with urlopen(f'https://api.github.com/rate_limit') as response: source = response.read() limit_data = json.loads(source) # Get User Repo Info with urlopen(f'https://api.github.com/users/{username}/repos') as response: source = response.read() user_repos = json.loads(source) created_at = data['created_at'] created_at = datetime.datetime.strptime(created_at, "%Y-%m-%dT%H:%M:%SZ") created_at = created_at.strftime("%B %d, %Y") context = { 'username': username, 'data': data, 'created_at': created_at, 'limit_data': limit_data, 'user_repos': user_repos, } return render(req, 'user.html', context) Here's my template user.html: <div class="repos"> <div class="top-repo"> <label for="top-repos" class="col-sm-3 col-form-label">Top Repos <span>by </span></label> <select class="custom-select bg-light text-primary"> <option selected="">stars</option> <option value="1">forks</option> <option value="2">size</option> </select> </div> {% for repo in user_repos %} <div class="card-deck"> <div class="card"> <div class="card-body"> <h4 class="card-title">{{repo.name}}</h4> <p class="card-text clearfix"> <i class="fas fa-circle"></i> {{repo.language}} <i class="fas fa-star"></i> {{repo.stargazers_count}} <i class="fal fa-code-branch"></i> {{repo.forks}} <span class="float-right">{{repo.size}} KB</span> </p> </div> </div> </div> {% endfor %} </div> -
How can i automatically update a field on a model in Django?
I am creating a chatting app, something like slack, I want to be able to update the participants' field on the Chat model for every new Contact on the website class Contact(models.Model): user = models.ForeignKey( User, related_name='friends', on_delete=models.CASCADE) friends = models.ManyToManyField('self', blank=True) def __str__(self): return self.user.username class Message(models.Model): contact = models.ForeignKey( Contact, related_name='author_messages', on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.contact.user.username class Chat(models.Model): name = models.CharField(max_length=20, default='Private Chat') participants = models.ManyToManyField(Contact, related_name='chats') messages = models.ManyToManyField(Message, blank=True) def __str__(self): return "{}".format(self.pk) -
How to store ipaddress and location in Django
I would like to store the IPaddress and location of all visitor, here is my code Model.py import uuid from django.db import models from django.urls import reverse from django.template.defaultfilters import slugify class Message(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) date = models.DateTimeField(auto_now_add=True) ipaddress = models.GenericIPAddressField(null=True,) email = models.EmailField(max_length=100) name = models.CharField(max_length=100,) message = models.TextField() slug = models.SlugField(null=False, allow_unicode=True, max_length=100, ) def __str__(self): return self.email def get_absolute_url(self): return reverse("message", kwargs={"pk":self.id, "slug":self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) return super().save(*args, **kwargs) View.py from django.views.generic.edit import CreateView from .models import Message class ContactPageView(CreateView): model = Message template_name = 'home/contact.html' fields = ['email', 'name', 'message'] The idea is, after the visitor submitting the contact form with the 3 fields shown in the view (email, name and message), I would like to automatically store his IPaddress and location too, so the point is, I don't know how to do that, just like I done with the date field in the model. Or if there is another way to solve this question, I'll appreciate your help, so just try to give me the solution editing or completing my code. NB: I know that I need edit my model to store the … -
Reverse for 'idnome' with arguments '('',)' not found. 1 pattern(s) tried: ['viewInscricao/(?P<pk_test>[0-9]+)/$']
in my views i do this: def home(request): if request.user.participant: current_user = request.user subscriptionUser = int(Subscription.objects.get(participant=current_user.participant).id) else: pass return render(request, template_name='inscricao/index.html', context={'getID':subscriptionUser} ) and in my html i do this: <a class="nav-link" href="{% url 'idnome' getID %}"> Consultar A Minha Inscrição </a> i have tried so many different ways, but i have no result. If i put a number instead of "getID" in the html, it works. If i let "getID" i get this: "Reverse for 'idnome' with arguments '('',)' not found. 1 pattern(s) tried: ['viewInscricao/(?P<pk_test>[0-9]+)/$']" if someone could help i woulb be appreciated -
unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta'
I am trying to update my status field based on timedelta(days=15). I read a few similar questions about this, and tried to code how you'll see. But when I try to load my page I am getting this error "unsupported operand type(s) for +: 'NoneType' and 'datetime.timedelta' ". What am I doing wrong? and I intend do a few tests more, the models is the best place to put this code? from datetime import date, timedelta class Status(models.Model): date_start = models.DateField(default = date.today) status = models.Chafield( default = 'Open', max_lenght = 255, choices = ( ('Open', 'Open'), ('Expired', 'Expired'), ), ) def __init__(self, *args, **kwargs): super(Status, self).__init__(*args, **kwargs) days = timedelta(days=15) self.date_expired = self.date_start + days self.date_today = date.today() def save(self, *args, **kwargs): if self.date_today > self.date_expired: self.status = 'Expired' super(Status, self).save(*args, **kwargs) -
how can i set a csrf token in FormData sended with XMLHttpRequest?
I'm trying to send to Django this FormData that way: const form = new FormData() form.append('name','Vitor') form.append('age',20) form.append('csrfmiddlewaretoken', '{{ csrf_token }}'); const request = new XMLHttpRequest() request.open('POST','my_form') request.send(form) request.onload = function(){ alert('sucess') } request.onerror = function(){ alert('error') } in Django: def my_form(request): ob = request.POST print('name: '+ ob['name'], 'age: '+ob['age']) return redirect('/') but the console gives me: [30/Jun/2020 20:27:12] "GET / HTTP/1.1" 200 419 [30/Jun/2020 20:27:12] "GET /static/script.js HTTP/1.1" 200 352 Forbidden (CSRF token missing or incorrect.): /my_form [30/Jun/2020 20:27:12] "POST /my_form HTTP/1.1" 403 2513 What can i do to set the CSRF token in this request? -
How to get liveserver to render django templates?
I've been messing around with a tutorial site, and I found that my VS Code LiveServer plugin doesn't work properly when I try to open Django templates. The CSS I applied is missing (although it renders correctly in my local development sever), and the template language code is actually printed to the screen rather than executed (see image below). My liveserver plugin appears to be working with html files outside of Django. (1) Right now I'm right clicking and selecting "Open with Liveserver." Is this wrong for Django? The liveserver docs recommend trying to "visit the Actual Server Address: http://localhost/[workspace], not the VS Code extension's Live Server Address: http://127.0.0.1:5500/". I tried including the file path in place of [workspace], but no luck. What do I do here? (2) I saw in another thread where someone recommended their own solution, here. I'm not sure where I'm supposed to run the './manage.py livereload' command, but it's not working in command prompt. What is the difference between './manage.py' and 'py manage.py'? And will this solution be any better than the VS Code plugin? -
Best practices for dealing with nested dicts?
I am loading data from a CSV to a db Model. I use an intermediate layer for data validation. Here's a basic example: {'Team': {'Account': {'InvoiceID' : invID, 'Amount': aLotOfMoney} }} for team in teams.: for account in teams[team]: for invoice in teams[team][account]: acc = Account(ID = teams[team][account][invoiceID], amount=teams[team][account][amount]) acc.save() This works fine and all but it's far from elegant and seems rather inefficient. Is there a way to return the nested Dict instead of the key? -
DJANGO - redirect() not redirecting - appends the current path name to the domain
Basically when a POST request is made, I want to redirect to another page. def sample(request): if request.method != "POST": return render(sample,"user/register.html") else: return redirect("https://www.djangoproject.com") This code works fine when it receives a GET request but when I submit information, instead of redirecting to the page above, it appends the the template name into the url, Something like this : http://localhost:8000/sample/sample No matter what I type into the redirect(), even completely random things it still redirects to sample/sample I've created multiple django-projects and in every one of them I still get this problem. -
Get Related Model From M2M Intermediate Model
In signals.py I am catching @receiver(m2m_changed, sender=Manager.employees.through). This is getting the signal sent when a m2m relationship is created between a Manager and an Employee. I am trying to get the Employee that this particular relationship is referencing. I am guessing sender is the 'through' relationship object, but really I'm not sure. If I print(sender) I get <class 'users.models.Manager_employees'>. I have tried referenced_employee = sender.employee_id, but this gives me <django.db.models.fields.related_descriptors.ForeignKeyDeferredAttribute object at 0x03616310>. print(sender['employee_id']) gives me 'ModelBase' object is not subscriptable. Thank you.