Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
csv.writer writing each character of word
I am trying to export a list of names from a Model like this: def export(request): response = HttpResponse(content_type='text/csv') writer = csv.writer(response) writer.writerow(['Location']) #header for launch in Location.objects.all().values_list('L_name'): export_data = zip_longest(*launch, fillvalue='') writer.writerows(export_data) response['Content_Disposition'] = 'attatchment'; return response Writerow is iterating on the characters of each name, producing a column of characters rather than names. Instead, I would like each name in its own row. Any ideas on how to achieve this? Thank you for any input. -
django websocket connection failed during web socket handshake in js console
I am trying django channels in my django projects. i have to fetch data from redis server and populate it in a datatable. I tried and established the code in my custom signin page, and the list of objects was printing there without an error. even connection had no error. but when i tries to connect it after logged in . it shows this error below in console. WebSocket connection to 'ws://localhost:8000/ws/data/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET -
How to auto-populate database field using data from other fields in the same model
I have a model called Coverletter with 4 fields: company, role, job_posting, content. I am trying to use the data from the first 3 fields to populate data in the 4th field. Right now, the user inputs values for 3 fields in a form: (company, role, job_posting) using a class based view CreateView. class CoverletterCreateView(LoginRequiredMixin, CreateView): model = Coverletter fields = ['company', 'role', 'job_posting'] template_name = 'coverletter/coverletter_create_form.html' def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form) def get_success_url(self): return reverse('coverletter:coverletter-create-content', kwargs={'pk': self.object.pk,} ) The user is then redirected to another class based view UpdateView via get_success_url, where the first three fields are showing with populated values. class CoverletterCreateContentView(LoginRequiredMixin, UpdateView): model = Coverletter fields = ['company', 'role', 'job_posting', 'content'] template_name = 'coverletter/coverletter_create_content_form.html' Right now the 4th field (content) is blank, but I am trying to populate the content field when the user submits the data from the first CreateView. The data is an html string that would look something like this: <p>Dear {{ company }} I am excited to be applying for the {{ role }} role.</p> I am very new to Django and web development, and am struggling to understand how to do this. I am unsure where in the app … -
I cant not get my data from my django form
I can't print my form.cleaned_data. Look like it the button that it not working correctly. When I press the buttom 'send' nothing is printed on my terminal. Thank you for the help im new to django. views.py from django.shortcuts import render from .forms import NameForm def get_name(request): if request.method == "POST": form = NameForm(request.POST) if form.is_valid(): name = form.cleaned_data["your_name"] message = form.cleaned_data["message"] print(name) print(message) else: form= NameForm() return render(request, "pools/home.html", {"form": form}) forms.py from django import forms class NameForm(forms.Form): your_name = forms.CharField(label="Your name" ,max_length=100) message = forms.CharField(widget=forms.Textarea) home.html {% extends "pools/base.html" %} {% load crispy_forms_tags %} {% block content %} <h1>Hello world</h1> <div class="content-section"> <form method="POST"> {% csrf_token %} {% crispy form %} <button class="btn btn-outline-info" type="submit">Send</button> </form> </div> {% endblock content %} -
How get only games with support json
I have a code def get_current_user_steam_games(user_id): return requests.get( f'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key={settings.STEAM_API_KEY}&' f'steamid={get_steam_id(user_id)}&format=json&include_appinfo=1').json()['response'] and this code show me on html it how i can get only name names of games? Thank you -
Django unit test "matching query does not exist"
I'm trying to unit test a model but I keep getting "Donation matching query does not exist," with the traceback pointing to the first line in the test_charity function. I tried getting the object with charity='aclu' instead of by ID, but that did not fix it. from django.test import TestCase from .models import Donation class DonateModelTest(TestCase): def init_data(self): #print("got here") x = Donation.objects.create(charity='aclu', money_given=15) # print(x.id) def test_charity(self): donation = Donation.objects.get(id=1) field_label = donation._meta.get_field('charity').verbose_name self.assertEquals(field_label, 'charity') My models.py: from django.db import models class Donation(models.Model): DONATE_CHOICES = [ ('aclu', 'American Civil Liberties Union'), ('blm', 'Black Lives Matter'), ('msf', 'Medecins Sans Frontieres (Doctors Without Borders)') ] charity = models.CharField( max_length=4, choices=DONATE_CHOICES, default='aclu' ) money_given = models.IntegerField(default=0) -
str vs repr, in django documentation shows str return instead of repr return
In the django doc https://docs.djangoproject.com/en/3.1/intro/tutorial02/ they add the str dunder but when they type the class in cmd, instead of showing the repr ugly object it shows the str return. My question is,why aren't we seeing the repr we simply see the class on cmd? shouldn't it show the str return text only when i print(class)? class Question(models.Model): question_text=models.CharField(max_length=200) pub_date=models.DateTimeField('date published') def __str__(self): return self.question_text #Make sure our str() addition worked. Question.objects.all() <QuerySet [<Question: What's up?>]> -
Django 404 error GET Request URL: http://localhost:8000/ keeps popping up when blank url is requested
I was following this tutorial by tom artyn. My code was exactly as his in the book, however, everytime i try to render my web page on the localhost server, i keep getting Page not found (404) Error. Here is my project(config) url: from django.urls import path, include from django.contrib import admin import core.urls urlpatterns = [ path('admin/', admin.site.urls), path('', include('core.urls', namespace = 'core')), ] Here is my app(core) url: from django.urls import path from . import views app_name ='core' urlpatterns = [ path('movies', views.MovieList.as_view(), name = 'MovieList'), ] Here is my app(core) view: from django.views.generic import ListView from core.models import Movie # Create your views here. class MovieList(ListView): model = Movie Here is my app(core) admin: from django.contrib import admin # Register your models here. from core.models import Movie admin.site.register(Movie) I have no clue why request doesn't match the '' url. Page not found (404) Request Method: GET Request URL: http://localhost:8000/ Using the URLconf defined in config.urls, Django tried these URL patterns, in this order: admin/ movies [name='MovieList'] The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display … -
django makemessages does nothing
When I run django-admin makemessages -l en nothing happens and no po files are created This is my folder structure /myproject myapp/ locale/ media/ static/ templates/ db.sqlite manage.py settings.py urls.py wsgi.py settings.py import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] 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', 'django_user_agents.middleware.UserAgentMiddleware', ] ROOT_URLCONF = 'urls' WSGI_APPLICATION = 'wsgi.application' LANGUAGE_CODE = 'fr' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [os.path.join(BASE_DIR, 'locale')] My folder structure is different because I moved settings.py, urls.py and wsgi.py to the project root, and I'm not sure if this is why makemessages is not working. -
Regular expressions and russian symbols in Django
I have the one url like this url(ur'^gradebook/(?P[\w\-А-Яа-я])$', some_view, name='some_view') and I expect it to process a request like ../gradebook/group='Ф-12б' but I get an error and the server crashes. Please help me figure out the Russian symbols -
Retrieving URL parameters in the order they are passed - django
I am trying to retrieve the URL parameters that are passed into the function, in the order they are acutally passed. The reason this matters, is its a payment provider integration, which calculates a hash from concatenating the values that are passed (in the order they are passed). So based on this, i need to access the parameters in the order they are passed in the actual URL, concatenate them and then add a MD5 key that is secret to my account to verify the request. For example: http://example.com/order/callback?date=20200101&currency=USD&txnid=1234567&hash=thegeneratedhas If i access the request through request.GET I get ordered dict. pseudo-code def callback(request): keys_concatenated = "" for value in request.GET: if value == "hash": pass else: keys_concatenated = keys_concatenated + request.GET[value] This generates a string like: USD202001011234567 The hash generated from the provider that the order is kept, and thus is expecting the value 20200101USD1234567 Defining the parameters within urls.py is not really something I want as the payment provider is openly saying that they might change parameters passed, and thus it would break the implementation. I also dont know the actual order they are passing it in from time to time. -
How to add a queryset column to another queryset?
I got this problem and I have searched about days and still dont figure it out how to solved it I have a queryset "q" that shows me a "model_id" and a column "available" And I want to add that column to the Model.objects.all() results, but the deal is that q is the result of a query to calculate the available amount so there is no table or model to refer Any suggestions or any solutions? Thxs for your time to read this ✌ -
How can the code in a views.py be tested?
def post(self, request, *args , **kwargs): form = self.form(request.POST) template_name= "spotify_calls/display.html" if form.is_valid(): cleaned = form.cleaned_data["SpotifyForm"] SpotifyAPI(client_data=" xxxxxxxxxxxxxxxx“, client_secret = "xxxxxxxxxxxxxxxxxxxxx") data = SpotifyAPI.search(self, query=cleaned , search_type="artiste") I want to determine if the method, SpotifyAPI.search(), actually worked and returned data in the data variable before I render it on a template. Expecting a dictionary in the data variable. Is there a way I could do this? -
Why is a part of my CSS style not applied?
Hii I'm kind of new so I might be making a rookie mistake but I have this HTML : {% extends 'base.html' %} {% load static %} {% block meta %} <title>HOME</title> {% endblock meta %} {% block style %} <link rel="stylesheet" href="{% static 'style.css' %}"> {% endblock %} {% block content %} <div class="content"> <h1>Test</h1> </div> {% endblock content %} and this CSS div.content { background-color: #DFBEBE; text-align: center; padding: 10px; height: 100%; } But it's not working... I tried with .content before but it also won't apply to my HTML. I applied a h1 css (with font) and it works just fine. It also works just fine with my previous projects(?) What did I do? -
Django-modeltranslation ValueError: Error adding translation field. Model already contains the field
I'm trying to implement localisation in a Django project by using django-modeltranslation. The documentation is pretty clear and straightforward and I've followed it to use it in my project. The problem is that when I try to migrate the models, I get a ValueError I cannot explain. Here is my code: settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'modeltranslation', 'core', 'blog', 'staticpages', ] # Default language LANGUAGE_CODE = 'en' # Languages supported by translation LANGUAGES = [ ('en', ('English')), ('es', ('Spanish')), ('es', ('Italian')), ] # Enable translations USE_I18N = True USE_L10N = True USE_TZ = True models.py # Create your models here. class Homepage(models.Model): slogan = models.CharField(max_length=500) about_text = models.TextField() translation.py from modeltranslation.translator import translator, TranslationOptions from .models import Homepage class HomepageTranslationOptions(TranslationOptions): fields = ('slogan', 'about_text') translator.register(Homepage, HomepageTranslationOptions) And this is the error I get: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/Andrea/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/Andrea/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/Users/Andrea/anaconda3/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/Andrea/anaconda3/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/Users/Andrea/anaconda3/lib/python3.6/site-packages/modeltranslation/apps.py", line 11, in ready handle_translation_registrations() File "/Users/Andrea/anaconda3/lib/python3.6/site-packages/modeltranslation/models.py", line 75, in handle_translation_registrations autodiscover() File … -
How to call a URL in Django and get response in Django screen
I have a external URL say (http://127.0.0.1:5000/getCombinations) I need to call this URL in my Django view and get output in Django screen only views.py from django.shortcuts import render import requests from django.http import HttpResponse import math def form(request): return render(request,'hello/output.html') def combination(request): n=int(request.POST.get("no")) respond= requests.post('http://127.0.0.1:5000/getCombinations') return render( request, 'hello/output.html', {'msg': respond['msg']}) output.html <body> <form action="combination" method="post"> {% csrf_token %} Enter number: <br/> <input type="number" name="no"> <br/> <input type="submit" ><br/> </form> I am getting " Response' object is not subscriptable" as error in my screen when I am using above code. there any way to call that URL in my screen -
Importing a Keras model into TensorFlow.js from Django Server
I want to import a Keras model from my Django to a web browser. This is how to fetch a Keras model from a web server // JavaScript import * as tf from '@tensorflow/tfjs'; const model = await tf.loadLayersModel('https://foo.bar/tfjs_artifacts/model.json'); It accepts URL as an argument. However the code inside this function sends another HTTP request for weights of a model. Namely group1-shard1of1.bin I can write such view to import json file def request_a_model(request): return render(request, ‚models/model.json’) but what with subsequent request for binary files? How can Django code handle these requests and send model.json file and weights as binary files? -
Django icontains does not work on all items
I have made a search function and was testing it out but found that it doesn't work on all my items. I am using MongoDB for my DB (Djongo). I have products with titles such as: Acrylic Paint Set Gaming PC Computer Stainless Steel Watch Cuisinart 15pc Cutlery Set The first two products I am able to find. But the last two I am not. My views.py def search(request): if request.method == "GET": query = request.GET.get("search") products = Product.objects.filter( Q(title__icontains=query)| Q(description__icontains=query) ) context = {"products": products, "query": query} return render(request, 'search.html', context) The html code: form action="{% url 'test:search' %}" class="form-inline my-2 my-lg-0" method="GET" > <input class="form-control mr-sm-2" type="text" name="search" id="id_q" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> I tried using a different approach by using the "django-filters" library but ran to the same problem. -
Django 'float' object has no attribute 'user' while using login decorator
I'm trying to build a django app and the app works, great so far. Right now i'm in the middle of making sure the user needs a login so they can log in. if the user is logged in than the user can use an machine-learning model to solve a problem. The error message I'm getting is 'float' object has no attribute 'user' and this started after I used the @login_required function in django. NOTE: The user is login in via the localhost:8000/admin/ panel Django provides. (later I will change that) after I fix this bug views.py def home(request): return render(request, 'home.html') @login_required def dashboard(request): return render(request, 'index.html') @login_required def getPredictions(temp_normal, hour,hour_x,hour_y): import pickle model = pickle.load(open("test_model.sav", "rb")) prediction = model.predict([[temp_normal, hour,hour_x,hour_y]]) return prediction @login_required def result(request): temp_normal = float(request.GET['temp_normal']) hour = float(request.GET['hour']) hour_x = float(request.GET['hour_x']) hour_y = float(request.GET['hour_y']) result = getPredictions(temp_normal, hour,hour_x,hour_y) return render(request, 'result.html', {'result': result}) html code index.html {% extends "base.html" %} {% block content %} <div class="content"> <div class="row"> <div class="col-lg-4"> <div class="card card-tasks"> <h1> </h1> <form action="{% url 'result' %}"> {% csrf_token %} <p>temp_normal:</p> <input class="form-control" type="text" name="temp_normal"> <br> <p>Weging:</p> <input class="form-control" type="text" name="Weging"> <br> <p>str:</p> <input class="form-control" type="text" name="straling"> <br> <p>hour:</p> <input class="form-control" type="text" … -
Django time auto_now_add in templates it's showing noon
Django time auto_now_add in templates it's showing noon how to resolve please help me -
<PYTHON DRF> Why am I getting only one value instead of list from request.data?
I have little problem with accessing to all values from request.data. Here my code and screens: My viewset: class LorebookViewset(ModelViewSet): queryset = Lorebook.objects.all() serializer_class = LorebookSerializer permission_classes = ( permissions.IsAuthenticated, ) def perform_create(self, serializer): data = self.request.data print(data) print(data['teams']) Serializer: class LorebookSerializer(serializers.ModelSerializer): teams = serializers.StringRelatedField(many=True, read_only=True) categories = serializers.StringRelatedField(many=True, read_only=True) author = serializers.StringRelatedField(read_only=True) class Meta: model = Lorebook fields = '__all__' Model: class Lorebook(models.Model): title = models.CharField(max_length=50, unique=True) cover = models.FileField(default='lorebooks/cover.jpg', null=True) thumbnail = models.FileField(default='lorebooks/thumb.jpg', null=True) banner = models.FileField(default='lorebooks/banner.jpg', null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() tags = ArrayField(models.TextField(), default=list) categories = models.ManyToManyField(Category) teams = models.ManyToManyField(Team) date_created = models.DateTimeField(auto_now_add=True) trailer = models.TextField() is_read = models.BooleanField(default=False) def __str__(self): return self.title Data in Postman: Print in perform_create in viewset: Why am I getting only last value from teams instead of list? -
How to add image using ajax jquery in django?
I am talking about how to show the image in the template after being submitted. I know how to do that with text but not File Field. If there is link or anything like that that ,that would be much appreciatd. -
DRF CursorPaginator how to know if second page?
I'm implementing a custom CursorPaginator from Django Rest Framework. I want to know if this is the second page (I know wrong terminology, but bear with me) that a user is in. To put a scenario in, if I navigated to a page that had no cursor, we name this page 1. If I navigate to the next page, I get a cursor. The problem I'm encountering is given that the user is in the second page, if I call self.previous_position or self.get_previous_link(), I'm only getting Page 1's cursor. How would I be able to know that the previous position is "page 1"? I was thinking of calling self.get_previous_link() by rebuilding the pagination object but passing in the previous cursor, i.e. page 1's cursor, but I can't seem to get it. -
Model with two ForeignKeys -- How to find objects that share a relationship?
I have a video hosting website, which features rock climbs. Each video can have multiple climbs. I am trying to add timestamps that are associated with the unique relationship of that specific video and that specific climb. So my models look like this: class Climb ... class Video climb = models.ManyToManyField('Climb', through='Timestamp', related_name='videos') class Timestamp climb = models.ForeignKey('Climb') video = models.ForeignKey('Video') time = models.IntegerField I can easily call all the timestamps associated with a video, and all the timestamps associated with a climb, but how do I find ONLY the timestamps that share a specific video and climb? For example, right now I can do the following: {% for video in videos %} {{video.id}} {% for climb in video.climb.all %} {{climb.name}} -- and now I want to be able to check for the timestamp that references both the video and the climb, and then call it here -- {% endfor %} {% endfor %} Thanks! -
In frontend PUT request returning Internal Server 500 error | Django Vue
I am trying to perform a PUT request in Vue view from DRF API backend. Though POST and GET requests are working properly in Vue(frontend) but for PUT request it's returning INTERNAL SERVER ERROR 500 Here is what I have done. settings.py INSTALLED_APPS = [ ..., 'rest_framework', 'corsheaders', 'articles' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } CORS_ALLOWED_ORIGINS = [ "http://localhost:8080" ] view.vue updateArticle(article) { axios .put('http://127.0.0.1:8000/api/' + article.id, this.article ) .then(response => { this.fetchArticle(); this.editArticle = null; return response; }) .catch(error => console.log(error)) } urls.py from .views import ArticleViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'', ArticleViewSet, basename='articles') urlpatterns = router.urls