Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the name of that HTTPS session recorder & playback tool that has an API? Alt. how would you automate an HTTPS website to do user functions?
I've successfully used the tool before. It has a local webpage UI that you goto in your browser that lists the https traffic that occured, and options to play it back. It also comes with a command line tool. I am thinking of a small word ending in "mt", but can't seem to get google to find it. If you can offer any other suggestions that would also be great. Also, would that be an acceptable way to automate an HTTPS session for a website? There's a website I have to automate for a job, and they provide no API to help do the things that users can do on the site, so I am automating from scratch. Thank you for any guidance. I am not allowed to use Selenium webdriver. The code will be hosted on a Django host and the frontend to the automation scripts will be a Django website. -
Tweepy Stream Stop/Start Programatically
I am trying to build a web application using Django to track tweets by hashtags. I am using Tweepy Asyncstreaming and it's working fine. I am new to async programming. I need help with how to stop the running stream and start a new stream when a new hashtag is added. Here is my code: import os from tweepy.asynchronous import AsyncStream import asyncio consumer_key = os.getenv('XXXXXXXXXXX') consumer_secret = os.getenv('XXXXXXXXXXX') access_token = os.getenv('XXXXXXXXXXX') access_token_secret = os.getenv('XXXXXXXXXXX') async def main(): stream = TweetStream(consumer_key, consumer_secret, access_token, access_token_secret) await stream.filter(follow=['web3', 'crypto']) class TweetStream(AsyncStream): async def on_connect(self): print('Stream connected') async def on_status(self, status): if status.in_reply_to_user_id == None and not(status.entities['user_mentions']): print(status.text) print(status.user.screen_name) async def on_error(self, status): print(status) if __name__ == '__main__': asyncio.run(main()) -
How to Search Tags in Wagtail
How do you search wagtail tags? This is my code for my search bar in my webapp: def search(request): search_query = request.GET.get('query', None) page = request.GET.get('page', 1) # Search if search_query: search_results = Page.objects.live().search(search_query) query = Query.get(search_query) # Record hit query.add_hit() else: search_results = Page.objects.none() Tags already have been set up. I tried using this code to make the tags in my model searchable but it didn't work: search_fields = Page.search_fields + [ index.SearchField('select_tags', partial_match=True), ] This is the webpage I looked at: https://docs.wagtail.io/en/stable/topics/search/indexing.html#wagtailsearch-indexing-fields -
How to prevent users from seeing all content in Django?
I have a website and I want to prevent visitors to seeing content unless they have permission. How can I restrict them? -
my website that based on Django and Nginx, can't be visited, instead, it downloads a blank file
I am getting this issue, only while requesting through the http protocol not ssl (https), I am using nginx for this server, all tags are correct(about content-types), nginx mime types settings are in standard status, and this is happening since a few days ago (earlier was fine)..! -
Django: get_absolute_url issue
I have been struggling through this issue for some time now... I have a model with two classes, and have a get_absolute_url function in both classes, but every time I try to use the function, I get the same response. models.py from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse # Create your models here. class Listing(models.Model): info = models.CharField(max_length = 200) def __str__(self): return self.info def get_absolute_url(self): return reverse('listing_detail', args = [str(self.id)]) class Application(models.Model): listing = models.ForeignKey( Listing, on_delete = models.CASCADE, related_name = 'applications', ) comment = models.TextField(max_length = 2500) def __str__(self): return self.comment def get_absolute_url(self): return reverse('applications', args = [str(self.id)]) urls.py from django.urls import path from .views import ListingListView, ListingDetailView, ListingApplicationView urlpatterns = [ path('', ListingListView.as_view(), name = 'listing_list'), path('<int:pk>/', ListingDetailView.as_view(), name = 'listing_detail'), path('<int:pk>/applications/', ListingApplicationView.as_view(), name = 'applications') ] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Listing, Application # Create your views here. class ListingListView(ListView): model = Listing template_name = 'listing/listing_list.html' context_object_name = 'listing_list' class ListingDetailView(DetailView): model = Listing template_name = 'listing/listing_detail.html' context_object_name = 'listing_detail' class ListingApplicationView(ListView): model = Application template_name = 'listing/applications.html' context_object_name = 'applications' templates <h2><a href="{{ listing.get_absolute_url }}">{{ listing.address1 }}</a></h2> <p><a href = "{{ applications.get_absolute_url … -
JWTAuth: KeyError
I want to inject JWTAuth into my chat project with websockets and I get this error when I go to the chat page, the chat itself does not work after I changed auth to my personalized JWT Can you please tell me what's wrong? Errors: HTTP GET /chat/lobby/ 200 [0.01, 127.0.0.1:60197] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:55592] Exception inside application: 'token' Traceback (most recent call last): File "C:\Users\ikoli\PycharmProjects\mychat\venv\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\ikoli\PycharmProjects\mychat\venv\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\ikoli\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\compatibility.py", line 34, in new_application instance = application(scope) File "C:\Users\ikoli\PycharmProjects\mychat\mychat\mychat\channelsmiddleware.py", line 25, in __call__ token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] KeyError: 'token' WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:55592] HTTP GET /chat/lobby/ 200 [0.00, 127.0.0.1:52491] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:63145] Exception inside application: 'token' Traceback (most recent call last): File "C:\Users\ikoli\PycharmProjects\mychat\venv\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\ikoli\PycharmProjects\mychat\venv\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\ikoli\AppData\Local\Programs\Python\Python39\lib\site-packages\asgiref\compatibility.py", line 34, in new_application instance = application(scope) File "C:\Users\ikoli\PycharmProjects\mychat\mychat\mychat\channelsmiddleware.py", line 25, in __call__ token = parse_qs(scope["query_string"].decode("utf8"))["token"][0] KeyError: 'token' WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:63145] consumers.py: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.user = self.scope["user"] self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name, self.user ) await self.accept() … -
Admin interface panel does not work when i assign user to a group in Django
When I click on button to assign a user to groups, page scroll to top of page and does not work This code is by inspect element on button: <li> <a title="Choose" href="#" id="id_groups_add_link" class="selector-add active">Choose</a> </li> I -
How do i write a jQuery input string so that it works with Django query string
Am working on a name search app but having a challenge getting it to work with Django query string, the challenge which i observed comes from my JavaScript input type with ${input} string when added to Django query string eg. "address/get-name/?search=${input}" doesn't return the query object or the payload data, instead it return an empty list, but when i make search through the browser it return all search query data eg "address/get-name/?search=smith", Now how do i get input through my scripts without having to use the java scripts query input type ${input} with django so let i get a query string like this "address/get-name/?search=james" ? Here is my script, Am a novice in JavaScript <script> new Autocomplete('#autocomplete',{ search : input => { console.log(input) const url = "/address/get-names/?search=${input}" return new Promise(resolve => { fetch(url) .then( (response) => response.json()) .then( data => { console.log(data.playload) resolve(data.playload) }) }) }, rennderResult : (result, props) =>{ console.log(props) let group = '' if (result.index % 3 == 0 ){ group = '<li class="group">Group</li>' } return '${group}<li ${props}><div class="wiki title">${result.name}</div></li>' } }) </script> my view.py def get_names(request): search = request.GET.get('search') payload = [] if search: objs = Names.objects.filter(name__startswith=search) for obj in objs: payload.append({ 'name' : obj.name }) … -
NameError at /login/ name 'user' is not defined line 26
Django Login, for some reason it doesn't work. Please help me I don't have much to explain this is my views.py. Whenever I login it sends the error, I'm making a login/logout/signup system. Below is part of the with the error in it. (Line 26 is the main error) Also this is part of Dennis Ivanov's course for Django but I can't seem to solve the error. from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from django.contrib import messages from .models import Profile from django.contrib.auth.models import User from .forms import CustomUserCreationForm, ProfileForm def loginUser(request): if request.user.is_authenticated: return redirect('profiles') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] try: user = User.objects.get(username=username) except: messages.error(request, "Username does not exist") user = authenticate(request, username=user, password=password) if user is not None: login(request, user) return redirect('profiles') else: messages.error(request, "Username OR Password is incorrect") return render(request, 'users/login_register.html') def logoutUser(request): logout(request) messages.info(request, "User was logged out") return redirect('login') -
Best way to trigger ML model in Django
Hello experienced Django guys, I'm developing my first app in Django with ML model for recommending books. I was wondering what is the most appropriate way to activate the python script clicking the button and taking the value from drop menu. To make it less confusing here is some code example: <!DOCTYPE html> <head> <title>Books</title> <body> <h1>Welcome to books recommender page!</h1> <br> <select> <option disabled = "True" selected>Select your favourite book!</option> {% for books in books %} <option>{{book.name}}</option> {% endfor%} </select> <button>Calculate my recommendations</button> </body> </head> Basically, I've connected Djagno app with Postgre DB with books, created this simple drop menu which shows all data in column. Now I want to pass the selected value to my python ML model (which is executing the function like this): try: print(get_recommendations(selected_book, n=6)) except: print("No book at stock.") Any suggestion how should I pass the drop menu value and trigger the script by clicking the button? -
MultilingualQuerySet always returns empty list
I have a website with support for 2 languages but I have a problem with switching url's. So when user clicks link that leads to some category I get list index out of range my model class Category(models.Model): category = models.CharField(max_length=20,unique=True) def __str__(self): return self.category translations.py for my model class CategoryTranslationOptions(TranslationOptions): fields = ('category',) translator.register(Category, CategoryTranslationOptions) my code view that is responsible for getting product with said category categoryList = Category.objects.all() categoryName = categoryList.filter(Q(category_pl=categorySlug) | Q(category_en=categorySlug)) productsInfo = Product.objects.filter(category=categoryName[0]) What I'm doing in categoryName is looking for name in two languages in case if user switches language mid browsing. Then I get the first value of it because it's a list but the list is empty. update when I printed out categoryList = Category.objects.all().values() I didn't saw any translation-related fields but i can see them in admin panel so it is the case of not getting correct query from database -
Wher to look for custom teplate tag in django
I'm trying to understand how netbox application is working (https://github.com/netbox-community/netbox). In a template "sidenav.html" it uses a custom tag "nav" this way: {% load nav %} {% nav %} Can you tell me what's behind that and where or how can I find it? -
List view and a dynamic List view in Django
I am brand new to Python & Django programming. I would like to display a List view category and a dynamic List view on the same Web page which will display a list of subcategories that belong to the selected category. -
How can I make a decorator in models.py?
I have a football Team class in my django Model. I made 3 methods of win, draw and lose where the self.Points_of_the_season will be modified accordingly ( +3 for win, +1 for draw and +0 for lose). But When I wrote those methods, I have to change the self.Match_Played with each call of the 3 methods. How can I make a decorator called @play_match which will add 1 to the concerned field? This is the code of models.py: class Team(models.Model): Team_name = models.CharField(max_length=255) Foundation_year = models.IntegerField() Points_of_season = models.IntegerField(default=0) Match_Played = models.IntegerField(default=0) League = models.ForeignKey(League, on_delete=models.CASCADE) def __str__(self): return f"{self.Team_name}-{self.Foundation_year}" @play_match def win(self): self.Points_of_season += 3 @play_match def draw(self): self.Points_of_season += 1 @play_match def lose(self): pass -
TF400898: An Internal Error Occurred. Activity Id: 1fc05eca-fed8-4065-ae1a-fc8f2741c0ea
i’m trying to push files into git repo via azure API but getting activity_id error. I followed their documentation and trying to add simple file in my repo. Here is my code: import requests, base64 pat_token = "xxxx-xxxxx-xxxx" b64Val = base64.b64encode(pat_token.encode()).decode() payload = { "refUpdates": [ { "name": "refs/heads/main", "oldObjectId": "505aae1f15ae153b7fc53e8bdb79ac997caa99e6" } ], "commits": [ { "comment": "Added task markdown file.", "changes": [ { "changeType": "add", "item": { "path": "TimeStamps.txt" }, "newContent": { "content": "# Tasks\n\n* Item 1\n* Item 2", "contentType": "rawtext" } } ] } ] } headers = { 'Authorization': 'Basic %s' % b64Val, 'Content-Type': 'application/json', } params = ( ('api-version', '6.0'), ) response = requests.post('https://dev.azure.com/{organization}/{project}/_apis/git/repositories/{repo}/pushes', headers=headers, data=payload, params=params) Anyone knows how to solve this issue? I have also added this issue on their developer community -
Why is current admin not shown in django app?
I created a mock user profile in Django admin in the admin/auth/user view and assigned the user with all permissions (active, staff status, superuser status). In admin/<app_name>/user I gave the user all authorization permissions. In the Django admin panel, when I hit view site and enter the home view of the django application, the current user is different from the one that was visiting the admin page. Why is the current user different from the admin user? -
Defining view function for displaying postgres data in django
I created the wines database in postgresql (containing ID, names etc), and inserted around 300 observations. I would like to display names of every wine in drop menu with django. The urls.py are properly setted up. App name inside the project is: jacques. What have I done so far: models.py from django.db import connection from django.db import models class ListWines(models.Model): name = models.CharField(max_length=200) views.py from django.shortcuts import render from jacques.models import ListWines def showallwines(request): wines = ListWines.objects return render(request, 'main.html', { 'name':wines } ) main.html <!DOCTYPE html> <head> <body> <select> <option disabled = "True" selected>Select your favourite wine!</option> {% for wines in showallwines %} <option>{{wines.name}}</option> {% endfor %} </select> </body> </head> The postgres database is named jacques (column containing data that I want to display is name) is connected with app by setings.py, however it doesn't show names. How should I redefine my functions in order to see display in main.html drop menu? -
Celery beat not sending task to worker in heroku, configured in a single dyno in free tier
I am making a website, where the user has to accept an agreement and then an expiration date is set for the user. On that date the contract is supposed to get expired by setting a contract_expired boolean field to True and sending an email to the respective user about the same. I used celery beat for this. Now since the site is in tessting phase, it is hosted in a free tier dyno in heroku, so I had to configure one dyno for web and the other for both celery worker and beat. I scheduled a task for beat where it would run daily on 9 am, to check the exipiries for the users and then do the work as mentioned above. This function was running correctly when I was testing it in the localhost, i.e., by running two seperate terminals for worker and beat. But today at 9 am it did not run in heroku. Below are the codes that i wrote for the entire process procfile release: python manage.py migrate web: gunicorn jgs.wsgi --log-file - celeryworker: celery -A jgs.celery worker & celery -A jgs beat -l INFO & wait -n celery.py from __future__ import absolute_import, unicode_literals import … -
How to use temporary file from form upload - Python Django
I have a form where users can upload up to 1,000 images at a time. I have changed my FILE_UPLOAD_MAX_MEMORY_SIZE in Django settings to 0 so all files uploaded via a form are written to a temp directory in my root folder. I am then trying to process the images with OpenCV. original_img = cv2.imread(temp_image.temporary_file_path()) gray = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY) temp_image.temporary_file_path() This returns the absolute file path of the temp image in a string format So I put that in the cv2.imread, however, it creates a NoneType instead of a numpy array like it should and then my program cannot run when it reaches gray = cv2.cvtColor(original_img,cv2.COLOR_BGR2GRAY) How do I read the temporary file into OpenCV? Any help is much appreciated. -
Issue finding which comment to reply to using django-mptt for nested comments in a blog
I'm trying to create a nested comment system with djano-mptt. I have got it working and the comments are displaying as designed. However, when the issue I'm having is coming up with the logic for the user to choose which comment to reply to. Through the form I can display all the post and parent field and that allows the user to select a post and comment. Although the issue being they can comment on any post and any comment in the list. Trying to implement logic where if the user is on that post they can only comment on that post and can choose which comment (if they want) to reply to. Here is the model: class Comment(MPTTModel): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=100) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class MPTTMeta: order_insertion_by = ['created_on'] def __str__(self): return f"Comment {self.body} by {self.name}" The view: def CommentView(request, pk): post = get_object_or_404(Post, id=request.POST.get('post_id')) comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): comment_form.instance.name = request.user.username comment = comment_form.save(commit=False) comment.post = post comment.save() else: comment_form = CommentForm() return HttpResponseRedirect(reverse('post_detail', args=[str(pk)])) The form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('post', 'body', 'parent',) labels = { … -
no such table: users_customuser in Django
I am trying to create an extended Custom User model that adds a level field of 0 to the User model which is not displayed on the form. But when I try to do this, I get the error no such table: users_customuser. I am new to Django. How can I implement what I described earlier and what I am doing wrong? Just in case I have done migrations... Here is a structure of the project: │ db.sqlite3 │ manage.py │ ├───ithogwarts │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py │ │ │ └───__pycache__ │ ├───main │ │ admin.py │ │ apps.py │ │ models.py │ │ tests.py │ │ urls.py │ │ views.py │ │ __init__.py │ │ │ ├───migrations │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ │ ├───static │ │ └───main │ │ ├───css │ │ │ footer.css │ │ │ header.css │ │ │ index.css │ │ │ │ │ ├───img │ │ │ │ │ └───js │ │ script.js │ │ │ ├───templates │ │ └───main │ │ index.html │ │ layout.html │ │ level_magic.html │ │ │ └───__pycache__ │ ├───templates │ └───registration └───users … -
jQuery .addClass applying to everything
I have a like button that uses jQuery. The like button works as expected however due to the way I have it setup it changes every icon on the page to a heart code: if (data.liked) { updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $("i").addClass("fa fa-heart-o liked-heart"); //problem line } else { updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $("i").addClass("fa fa-heart-o unliked-heart"); //problem line From what i userstand the issue is that I am appending the class fa fa-heart-o ... to all i elements. How can I just apply it to the like button full code: <script> $(document).ready(function(){ function updateText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $(".like-btn").click(function(e){ e.preventDefault() var this_ = $(this) var likeUrl = this_.attr("data-href") var likeCount = parseInt(this_.attr("data-likes")) | 0 var addLike = likeCount + 1 var removeLike = likeCount - 1 if (likeUrl){ $.ajax({ url: likeUrl, method: "GET", data: {}, success: function(data){ console.log(data) var newLikes; if (data.liked){ updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $( "i" ).addClass( "fa fa-heart-o liked-heart" ); } else { updateText(this_, data.likescount, "") $(".like-btn").prepend("<i></i>"); $( "i" ).addClass( "fa fa-heart-o unliked-heart" ); } }, error: function(error){ console.log(error) console.log("error") } }) } }) }) </script> <a class="like-btn" data-href='{{ post.get_api_like_url }}' data-likes="{{ post.likes.count }}" href="{{ post.get_like_url }}"><i class="{% if userliked %}fa fa-heart-o … -
AttributeError: 'FlaubertForSequenceClassification' object has no attribute 'predict'
I am trying to classify new dataset from best model after loading but I get this error: best_model_from_training_testing = './checkpoint-900' best_model= FlaubertForSequenceClassification.from_pretrained(best_model_from_training_testing, num_labels=3) raw_pred, _, _ = best_model.predict(test_tokenized_dataset) predictedLabelOnCompanyData = np.argmax(raw_pred, axis=1) Traceback (most recent call last): File "/16uw/test/MODULE_FMC/scriptTraitements/classifying.py", line 408, in <module> pred = predict(emb, test_model) File "/16uw/test/MODULE_FMC/scriptTraitements/classifying.py", line 279, in predict raw_pred, _, _ = model.predict(emb_feature) File "/l16uw/.conda/envs/bert/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1130, in __getattr__ raise AttributeError("'{}' object has no attribute '{}'".format( AttributeError: 'FlaubertForSequenceClassification' object has no attribute 'predict' -
Run Djano Project On Github
I am new on Full Stack developer. I make a Django project it is run on localhost:8888. I want to run it on github. But I don't know how i do it. Please, Help me. How i run Django project on Github.