Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dropdown navbar menu on my Django/Bootstrap 4 website works everywhere except on the home page
As the title says, I have a dropdown menu on my site. At first it only worked on the homepage and nowhere else until I realised I didn't include the link to the Bootstrap JavaScript framework in the base.html file. So I included it and now the dropdown menu works everywhere except on the homepage. I feel like this is a simple fix and is just staring me in the face but it has me stumped. Any help is appreciated. Here is the base.html {% load static %} <!DOCTYPE html> <html> <head> <title>TUD Cinemas</title> <!-- My own CSS Link --> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <!-- Bootstrap CSS Link --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <!-- Google font link --> <link href="https://fonts.googleapis.com/css?family=Montserrat:500&display=swap" rel="stylesheet"> </head> <body> <nav class="navbar navbar-expand-lg navbar-light sticky-top"> <div class="container"> <a class="navbar-brand" href="{% url 'home' %}"> <img src="/static/images/TUDC_logo.png" class="luke_logo"> </a> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'home' %}">Home<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'movies' %}">What's on</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'blog' %}">Blog</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'news' %}">News</a> </li> {% if request.user.is_authenticated %} <!-- Dropdown Menu --> <li class="nav-item dropdown multi-level-dropdown"> <a href="#" id="menu" data-toggle="dropdown" … -
Django admin page looks different when deployed to the web host
I have seen this problem posted and people have answered in a number of ways, which I have tried, but I am still having issues with the deployed version looking different than when it is on localhost. I tried using the collectstatic command, but it still looks weird and ugly. I removed some things from this post, such as the secret key and database info. Here is my settings.py: ALLOWED_HOSTS = ['acrms-mis446-2020.herokuapp.com', 'localhost'] # Application definition INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'carts', 'orders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mis446.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mis446.wsgi.application' # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles') STATIC_URL = '/static/' LOGIN_REDIRECT_URL = 'ACRMS-Home' -
Table Pagination [Bootstrap - Django]
I'm working on a django-bootstrap project and i'm having some trouble with the bootstrap's table pagination, it won't appear on my template. I'm using one of the default's bootstrap tables with my own styles, and i wanted to ask you guys for your help to give my table the pagination it needs. <table id="table1" class="table table-bordered table-striped" style="width:1200px; margin-left:-45px"> <thead > <tr> <th class="header1"> </th> <th class="header1">ID Riesgo</th> <th class="header1">Código Riesgo</th> <th class="header1">Característica</th> <th class="header1">Evento</th> </tr> </thead> <tbody> {% for riesgos in riesgos %} <tr style="height: -2px;"> <td style="text-align:center;"> <div class name="checkboxWrapper"> <input type="checkbox" id="check" hidden="true" style="margin-top: 10px;"/> <label for="check" class="checkmark" ></label> </div> </td> <td style="color:#A9A9A9 ;">{{riesgos.id_ri}}</td> <td style="color:#A9A9A9;">{{riesgos.cod_ri}}</td> <td style="color:#A9A9A9;">{{riesgos.caracterisitica}}</td> <td style="color:#A9A9A9;">{{riesgos.evento}}</td> {% endfor %} </tr> </tbody> </table> Thanks everyone! -
Python Elasticsearch - error during --populate
could someone help me understand this error below? Your operating system name and version: [enter image description here][1] Any details about your local setup that might be helpful in troubleshooting: elasticsearch==6.3.1 elasticsearch-dsl==6.1.0 django-elasticsearch-dsl==0.5.1 Detailed steps to reproduce the bug: [enter image description here][1] Lib: https://github.com/sabricot/django-elasticsearch-dsl Code: documents.py from elasticsearch_dsl import analyzer, tokenizer from django.utils.html import format_html from django.db.models.query import QuerySet from apps.comprasnet.models import PregaoItens, PregaoWeb, UasgWeb, Modalidade, TermoHomologacao pregaoitens = Index('pregaoitens') pregaoitens.settings( number_of_shards=1, number_of_replicas=0 ) @pregaoitens.doc_type class IndexPregaoItens(DocType): licitacao = fields.ObjectField(properties={ 'licitacao_id': fields.TextField(), }) uasg = fields.ObjectField(properties={ 'co_uasg': fields.IntegerField(), 'uf': fields.TextField(), }) modalidade = fields.ObjectField(properties={ 'codigo': fields.IntegerField(), }) # index.map.totalfields.limit termo = fields.ObjectField(properties={ 'id': fields.TextField(), }) descricao = fields.TextField( fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() }, fielddata=True, analyzer='keyword' ) html_strip = analyzer( 'html_strip', tokenizer="whitespace", filter=["lowercase", "snowball", "stemmer", "asciifolding", "trim"], char_filter=["html_strip"] ) descricao_comp = fields.TextField( analyzer="standard", fields={ 'raw': fields.KeywordField(), 'suggest': fields.CompletionField() } ) uasg_name = fields.TextField( analyzer=html_strip, fields={'raw': fields.KeywordField()} ) uf = fields.TextField(fielddata=True) valor_estimado = fields.FloatField() lance_per = fields.FloatField() desconto_nego = fields.FloatField() lance_real = fields.FloatField() valor_nego = fields.FloatField() valor_equalizado = fields.FloatField() valor_total = fields.FloatField() bec_proposta_valor = fields.FloatField() unidade_id = fields.TextField(fielddata=True) class Meta: model = PregaoItens related_models = [PregaoWeb, UasgWeb, Modalidade, TermoHomologacao] fields = [ 'id', 'nu_pregao', 'modalidade_desc', 'objeto', 'dt_entrega_proposta', 'dt_abertura_proposta', 'dt_homologacao', 'download_link', … -
Updating only certain object's div in Django using jQuery
I am trying to update the DOM, whenever a user likes a post and displays the number of likes on a post. However, I realized my function will update all the classes on the pages and not only the certain post being liked (When a user clicks on thmbs up, all the thumbs up buttons change to dumbs down) my function for changing the like: function like_post() { // newly added $('#like-section #likeBtn').on("click", function (e) { e.preventDefault(); if($("#like-section #likeBtn i").hasClass("fa-thumbs-up")){ ($("#like-section #likeBtn i").removeClass("fa-thumbs-up")) ($("#like-section #likeBtn i").addClass("fa-thumbs-down")) } else { ($("#like-section #likeBtn i").removeClass("fa-thumbs-down")) ($("#like-section #likeBtn i").addClass("fa-thumbs-up")) } }); // end } my posts HTML template in Django: {% load static %} <link rel="stylesheet" href="{% static 'css/post/style.css' %}"> <script src="{% static 'js/like-api.js' %}"></script> <script src="{% static 'js/post.js' %}"></script> {% for post in posts %} <script> $(document).on('click', '.post-detail-clickable-details-view', function () { var url = $(this).attr("data-url") document.location.href = url }); </script> <div class="row ml-2"> <div class="col-sm-2"> <div class="float-right mb-3 mt-3"> <div> <img class="img-create-post rounded-circle mr-2" src="https://mdbootstrap.com/img/Photos/Avatars/avatar-5.jpg" alt="Profile image"> </div> <div> <p class="text-muted post-card-date small mr-2">{{ post.get_created_on }} ago</p> </div> </div> </div> <div class="col-md-10" style="margin-left: -1.6rem;"> <div class="card rounded-0 mb-3 mt-3"> <div class="card-header bg-transparent" style="height: 3rem;"> <h5 style="margin-bottom: 0px;"> <a class="text-dark" style="text-decoration: none;" href="{% url … -
Serve medias as static django
I have a template where I want to iterate through the Massage objects of the Massage Model. I'm using a for loop in my gabarit. My problem is that I need to upload the image for each massage and then serve it with boto3 using S3 storage. This make the loading of my page longer. Is there a way to store these media files as statics? So I can serve it with Whitenoise? class Massage(models.Model): nom = models.CharField(max_length=120) nom_traditionnel = models.CharField(max_length=120, default="", blank=True) description = models.TextField() image = models.ImageField(blank=True, null=True, upload_to='image/') Thanks for you help. -
Django Model Form not saving NULL data
I have the following form, view and model form, the Django version is 3.0 and the original DB is written in PostgreSQL, the form is submitted via ajax. class Model(models.Model): depth = models.FloatField(blank=True, null=True) from_field = models.FloatField(blank=True, null=True) to = models.FloatField(blank=True, null=True) interval = models.FloatField(blank=True, null=True) class Meta: managed = False class Form(forms.ModelForm): class Meta: model = Model fields = ['depth', 'from_field', 'to', 'interval'] @csrf_exempt def AddData(request): form = Form(request.POST) if form.is_valid(): form.save() When AddData is executed there is no errors but with the data being something like: depth=30, from_field=null, to=null, interval=null The data saved in the database is: depth=30, from_field=0, to=null, interval=null Could this be because the model has the parameter managed=False? I've checked the data sent by the template and when it's received by the view and the null data reflects correctly in DB except for from field. -
Django filter: Many to Many specific field to custom Group field
This is probably not the best way to go about user permissions- though I have a list of User Groups that contain names of Markets and a custom field built in containing the "Market_id". Within the models I am filtering, I have a ManytoMany relationship linked to another model named "Markets". The "Markets" model also has a "market_id" field. How can I go about giving the user only the objects that are within their "Market" or group?: Models I am filtering: class Opportunity(models.Model): opportunityid = models.CharField(max_length=500, blank=True) market = models.ManyToManyField('Market', related_name ='market', blank= True) Market model- M2M relationship: class Market(models.Model): marketname = models.CharField(max_length=500) market_id = models.CharField(max_length=100, blank=True) def __str__(self): return self.marketname My attempt at the queryset- currently returns a blank queryset, even though my user has permissions for all markets or groups: class projectViewSet(viewsets.ModelViewSet): serializer_class = ProjectSerializer authentication_classes = [SessionAuthentication] permission_classes = [IsAuthenticated] def get_queryset(self): user = self.request.user groups = user.groups.all() finalgroups = [] for g in groups: finalgroups.append(g.market_id) queryset = Opportunity.objects.all() queryset = queryset.filter(market__market_id__in = finalgroups) return queryset Thanks for your time! -
Django Content Security Policy Allow Sitemap.xml and Robots.txt
I am using https://django-csp.readthedocs.io/en/latest/ and I cannot figure out how to get the content security policy to allow the sitemap.xml file and robots.txt file. The sitemap.xml file I am generating automatically using https://docs.djangoproject.com/en/3.0/ref/contrib/sitemaps/. The robots.txt file I am using https://django-robots.readthedocs.io/en/latest/ CSP error (applies to both): Refused to apply inline style because it violates the following Content Security Policy directive: "style-src..... Sitemap.xml: prepareWebKitXMLViewer@VM709:30(anonymous)@VM709:383 <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> ........ "use strict"; var nodeParentPairs = []; var tree; function prepareWebKitXMLViewer() { var html = createHTMLElement('html'); var head = createHTMLElement('head'); html.appendChild(head); var style = createHTMLElement('style'); style.id = 'xml-viewer-style'; head.appendChild(style); var body = createHTMLElement('body'); html.appendChild(body); var sourceXML = createHTMLElement('div'); sourceXML.id = 'webkit-xml-viewer-source-xml'; body.appendChild(sourceXML); var child; while (child = document.firstChild) { document.removeChild(child); if (child.nodeType != Node.DOCUMENT_TYPE_NODE) sourceXML.appendChild(child); } document.appendChild(html); var header = createHTMLElement('div'); body.appendChild(header); header.classList.add('header'); var headerSpan = createHTMLElement('span'); header.appendChild(headerSpan); headerSpan.textContent = "This XML file does not appear to have any style information " + "associated with it. The document tree is shown below."; header.appendChild(createHTMLElement('br')); tree = createHTMLElement('div'); body.appendChild(tree); tree.classList.add('pretty-print'); window.onload = sourceXMLLoaded; } Robots.txt: User-agent: * Disallow: Host: example.com -
Global Variable Not Updating In Django View
I am trying to loop through users on a certain AJAX request and assign a different value to a global variable once I get the data returned to my django view from AJAX. Inside the if statement, the variable prints correctly, however, when I try to access it in the view's context dictionary, it retains it's old value and does not update. views.py def view_profile(request): g = Friend.objects.all() j = forms.FriendForm() s = forms.SearchForm() h = UserProfileInfo.objects.all() global term term = [] global r r = [] global e e = h[0] global friend_arr friend_arr = [] global messages messages = [] if len(g) != 0: for x in g: if x.user == request.user.username: friend_arr.append(x) else: pass if request.method == "POST": s = forms.SearchForm(request.POST) j = forms.FriendForm(request.POST) if request.is_ajax(): if list(request.POST)[0] == 'friend': friend = request.POST['friend'] for x in range(0, (len(h) - 1)): if str(h[x]) == str(friend): e = h[x] break else: pass elif list(request.POST)[0] == 'to_be_messaged': t6t6 = request.POST['to_be_messaged'] new_arr = t6t6.split('+') global action global user action = new_arr[0] user = new_arr[1] messages = MessageModel.objects.filter(user=request.user.username, to_user=user) else: d = MessageModel.objects.get_or_create( user=request.user.username, to_user=user, message=request.POST['message_text'], )[0] d.save() # return HttpResponse('') print(e) if s.is_valid(): term = ArtistCount.objects.filter(user__icontains=(s.cleaned_data['friend'])) if j.is_valid() and request.POST.get('sReq') is … -
NOT NULL constraint django
I am trying to create a cart model using ForeignKey relation with User. My models.py: class cart(models.Model): item = models.OneToOneField(products, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, blank=True, default=None, on_delete=models.CASCADE) def __str__(self): return self.item.name I am getting a error like this: django.db.utils.IntegrityError: NOT NULL constraint failed: new__mall_cart.user_id I have provided null=True as well as blank=True and the superuser is created with the name of admin. What is issue here? Also, I don't want the user field to be null neither it to be blank. How can I resolve this? -
Get count from other url (DRF)
Early, I did create answer - Count objects using Django Rest Framework Now, I want to add a field with an image URL. I want to create like this - { "brand" : "Some name", "count": Int, "image": "some path to image.jpg" } How to create it? -
Different login views with Custom User
My goal is to have two views for login: one with email and password, and another with username and password. Created a custom user class named MyUser extending from AbstractBaseUser. In that user class, stablished USERNAME_FIELD = 'email' Django by default uses the username field for authentication purposes of a user. When i want users to login with email, that's easy now. But how can I do to create another view that logs in with just username and password (instead of the email)? -
why django admin shows 2 duplicated queries for foreignkey field in djang debug toolbar?
i have a model which use foreignkey. for example POST model use foreignkey for Category Model. when i use django debug toolbar in django admin, it shows 2 duplicate times/ 2 similar queries for foreignkey field. what is the problem and how to fix it? -
Why does my page display all blog entries even after applying pagination
Please help here. I am displaying blog entries in a page in my application. All entries keeping displaying even after setting the views to display 2 entries per page. Views.py page = request.GET.get('page', 1) paginator = Paginator(blog_post,2) try: blog_page = paginator.page(page) except PageNotAnInteger: blog_page = paginator.page(1) except EmptyPage: blog_page = paginator.page(paginator.num_pages) context = { 'blog':blog_page, 'page':page, } return render(request, 'webpages/blog.html', context=context) Blog.html <div class="blog-pagination"> {% if blog.has_other_pages %} <ul class="justify-content-center"> {% if blog.has_previous %} <li><a href="?page={{ blog.previous_page_number }}"><i class="icofont-rounded-left"></i></a></li> {% else %} <li class="disabled"><i class="icofont-rounded-left"></i></li> {% endif %} {% for i in blog.paginator.page_range %} {% if blog.number == i %} <li class="active"><a href="">{{ i }}</a></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if blog.has_next %} <li><a href="?page={{ blog.next_page_number }}"><i class="icofont-rounded-right"></i></a></li></a></li> {% else %} <li class="disabled"><i class="icofont-rounded-right"></i></a></li></li> {% endif %} </ul> {% endif %} -
Can't make Django raw sql working correctly
I need to make inner join query like this: SELECT * FROM accounting_supplier as s LEFT JOIN ( SELECT position, supplier_id FROM accounting_supplierposition WHERE user_id = %s ) as sp on sp.supplier_id = s.id ORDER BY sp.position", [request.user] Models look like: class Supplier(models.Model): name = models.CharField(max_length=512) short_name = models.CharField(max_length=100, unique=True) class SupplierPosition(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) position = models.PositiveIntegerField() I've tried different approaches but no one gives the result I want. There is a way described here: Django Left Outer Join but distinct does not work with MySQL, so I decided to use RAW. But it seems that ordering doesn't work correctly. If I copy/paste sql from my code to mysql command line it works fine but in Django it does make selection but no order. Any suggestions? Thank you. -
Django - How to create a dedicated table to an element of a model?
I have two Models named Food and Unity. For each food I create I want to have a specific dedicated Unity table to the food being created. So if I create a food called Orange, I want it to have an instance of Unity specific only to Orange. Unities represent a measure of weight, like grams, cup, spoon etc. I tried Many to Many Fields but when I create a food and I want to choose Unities, all the unities from all foods appear mixed in the select field(not an option). How can I do this? -
Django as from end for Selenium
Is it possible to setup a Django website, that will give the front end users accsses to run pre-coded script for Selenium automation under the hood? by default as headless browser. Each with his own cookies, dashboard, proxies for relevant accounts ect. I've seen some basic GUI which people have created with Python libararies, and the final outcome seems quite incomplete for an actual produect. On top of that, it seems a lot harder to create a SaaS app that fits for Windows, Linux, Firefox, Chrome ect rather than on the website server. -
Django-filter with checkboxes instead of option list
I have a model containing three fields: title= models.CharField(max_length=250) cat1 = models.CharField(max_length=250, choices=(('g1',"Game1"), ("g2", "Game2"), ("g3", "Game3"), ("g4", "Game4"))) cat2 = models.CharField(max_length=250, choices=(('type1',"Drawn"), ("type2", "Computer graphic"), ("type3", "Pixelart"))) And in filters.py I have: import django_filters from .models import MyModel from django import forms class ArtFilter(django_filters.FilterSet): class Meta: model = MyModel fields = ['cat1', 'cat2', ] Don't know if views.py does matter in this case, but here it is: def search(request): art_list = MyModels.objects.all() art_filter = ArtFilter(request.GET, queryset=art_list) return render(request, 'search/art_search.html', {'filter': art_filter}) Everything's fine except that I need to let people choose more than one game or art type, so they could click on Game1, Game2 and Drawn to see all drawn images from both games. How can I achieve this? -
How to loop through model and display it on the modeladmin in django?
i'm new to python and django and stackoverflow too. Id like to know if there is a way to display on my admin section the number of party that an author have in the Author admin section call num_party ? To me i have to loop through the model and count how many party an author has, it's seems easy to say but not easy to do, so someone could help me ? Here my Party Model class Party(models.Model): title = models.CharField(max_length=200) place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) date = models.DateField(null=True, blank=True) genre = models.ManyToManyField(Genre, help_text='Select a genre for this partty') ticket_available = models.IntegerField() ticket_price = models.PositiveIntegerField(default=5) language = models.ManyToManyField('Language') insider_secret = models.ManyToManyField('InsiderSecret') #benef = models.IntegerField(default=5) def get_benef(self): return self.ticket_available * self.ticket_price benef = property(get_benef) def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) def display_genre(self): return ', '.join(genre.name for genre in self.genre.all()[:3]) display_genre.short_description = 'Genre' def display_secret(self): return ', '.join(insider_secret.secret for insider_secret in self.insider_secret.all()[:3]) display_secret.short_description = 'Insider Secret' class Author(models.Model): """Model representing an author.""" username = models.CharField(max_length=100, help_text="How do you want to be call by people as organisor ? ", default="Bestpartyorganisorintown") first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) class Meta: ordering = … -
django search only some words in a precise order
Hi I'm using django in Mayna EDMS index function to search only some words in a precise order within a text. For example I need to search: "Date: * ** * 2020 alle ore" where "*" character could be any character. How can I manage this search ? -
Run a bash script from another user with Django
this is my first Django project, I apologies if I say some nonsense To start a game server, I have to login with ssh as the user running the server, then type./server start to start it. I want to be able to run this command from a webapp. As of now, I've managed to do this on Django. What I want to do is that when I press the "Start" button, this commands run on the server side: su - gameuser -c '/home/gameuser/server start' > /dev/null 2>&1 The problem I'm facing is that I don't know how to login as the gameuser since I'm not a running the webapp as a sudo user. How can I approach this problem? Thanks in advance :D -
Override Django's AuthenticationForm's fields
I am using Django's autentication backend and it works fine, but I want to give the username and password fields a custom css class. I have been trying to look for a solution but I cannot find anything here or anywhere else. This is what I have done so far: project/forms.py: from django import forms from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control form-control-lg'})) project/urls.py: from django.contrib import admin from django.urls import path, include from .forms import LoginForm urlpatterns = [ path('accounts/', include('django.contrib.auth.urls'), {'authentication_form': LoginForm}), ] accounts/login.html: <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.username }} {{ form.password }} <button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button> </form> The login system works but I cannot get the css changes to show up. I inspected the username and password fields but they are not showing up in the browser at all. I am guessing I am missing something somewhere? Any help would be really appreciated! -
Sort Blog Post comments by date DJANGO
Hi i have a problem with comments on my Blog app in Django. Everything is working fine except that i want to display comment sorted by date (newest on top) o and it'll be great i'll be able to put in to the author field user that is actually loged in.. TY views.py @login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post-detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': form}) models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') author = models.CharField(max_length=100) text = models.TextField() created_on = models.DateTimeField(default=timezone.now) active = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text', 'created_on') -
How to get data from nested HTML using BeautifulSoup in Django
I am trying to learn web scraping and I'm stuck at a point where the data I want is wrapped by a div tag as so: <div class="maincounter-number"> <span style="color:#aaa">803 </span> </div> There are several data like that and I need all (eg. 803). So i guess I need to do soup.find_all(...) but I don't know what to put inside. Anyone help? I am working in python (Django.)