Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pivotal/Django settings for user provided MSSQL database
I deployed a django application on Pivotal Cloud Foundry. While in development, I just stuck with the built in sqlite database while getting the UI together (didn't need to retain data so pushing/deleting wasn't an issue). I've since developed an MSSQL back end in an on-prem server (Azure..but on prem). My organization doesn't allow public IP services, so anything other than spring applications in Pivotal isn't allowed. On my Windows laptop, I have no issue speaking to the database (settings.py): ''' DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': 'xxx.database.windows.net', 'Port': '', 'NAME': 'Django_Admin', 'OPTIONS':{ 'driver': 'ODBC Driver 17 for SQL Server', 'username': 'xxx', 'PWD': '***', 'Authentication': 'ActiveDirectoryPassword', } } } ''' When I deploy to PCF, however, I receive the error "('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)")" And I get the error for any driver I try...17,13,w/e... I created a user provided service in PCF using my database's connection string. How do I call that user provided service in my settings.py? I found how to call it if it was a PCF provided services, but how would I call it since it's a user provided service? Thanks … -
Take data from database with javascript
In a Javascript function I need data from the database. What should I use XMLHttpRequest or fetch() or Ajax? I tryed the first one but somewhere I read is old and fetch() is to be prefered. I'm a beginner, anyway my file.js: function FilterBy(selezione) { ... var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { document.getElementById("test").innerHTML = this.responseText; } }; //xhttp.open("GET", "lists/getlistname/?m="+maschio+"&f="femmina+"&n="neutro+"&l="linguaggio+"&i="initial", true); //xhttp.open("GET", "/lists/getlistname/?maschio=True", true); xhttp.open("GET", "/lists/getlistname/", true); //xhttp.send("m="+maschio+"&f="+femmina+"&n="neutro+"&l="linguaggio+"&i="initial"); xhttp.send("maschio=True&femmina=False&neutro=False&linguaggio=romano&initial=a"); } I made some tentative but the parameters doesn't arrive to my view. Also can I use a url django style, like lists:getlistname? here my url.py: urlpatterns = [ ... path('getlistname/', views.getlistname, name='getlistname'), ] my views.py: def getlistname(request, maschio, femmina=True, neutro=True, linguaggio='tutti', initial='0'): ... return HttpResponse('hi') So, what happens? the view getlistname is called but the parameters aren't passed (it uses the default). -
design student results database with django
i'm looking for advice to improve my database design in order to get better result i'm trying to create an online system for a high school grade results with django something like that : the admin enter the marks for each subject in courses? teen = '10th' eleven = '11th' twelve = '12th' class_choices = ( (teen , teen), (eleven , eleven), (twelve , twelve),) male = 'male' female = 'female' gender = ((male , male), (female , female),) 1st = '20' 2nd = '30' 3rd = '20' 4th = '30' seasons = ((1st , 1st), (2nd , 2nd) (3rd , 3rd), (4th , 4th)) class ClassLevel(models.Model): class_level = models.CharField(max_length=20 , choices=class_choices , default='' , unique=True) courses = models.ManyToManyField(Courses) class StudentProfile(models.Model): student_id = models.CharField(blank=True , max_length=30) name = models.CharField(max_length=20) middle_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) image = models.ImageField(upload_to='profile_images/' , default='logo.png') class_level = models.ManyToManyField(ClassLevel) gender = models.CharField(choices=gender ,default=male, max_length=10) date_of_join = models.DateTimeField(default=datetime.datetime.now) class Courses(models.Model): season = models.CharField(choices=seasons , max_length=10) math = models.PositiveIntegerField() science = models.PositiveIntegerField() english = models.PositiveIntegerField() physic = models.PositiveIntegerField() chimestry = models.PositiveIntegerField() def pre_save_student_id(sender,instance , *args,**kwargs): if not instance.student_id: instance.student_id = generate_id(instance) pre_save.connect(pre_save_student_id,sender=StudentProfile) is it fine or there is a better design to achieve the absolute solution -
How do I delete sessions when a user logs out Django?
I'm learning Django. I created the Sign out function. But when I loop with for it gives an error. My Code: def logout(request): for key in request.session.keys(): del request.session[key] return redirect('login') But get this error ? I am using Python 3. Can you help me ? RuntimeError at /logout/ dictionary changed size during iteration -
How can I use a model instance to filter a queryset in django
I'm new to Django and I need to declare a field wich stores the number of trials of a delivery, and for that I need to verify how many delivery trials were attempted for a given package, but when I try to filter the objects where package_id is the same from the current certification I get an error Saying 'self' is not defined. what am I doing Wrong? I've tried before using models.F('package_id') instead of self.package_id, but this gives me all objects because it checks the package_id of each instance against itself. class Package(models.Model): content = models.CharField(max_length=150) weight = models.FloatField() destiny = models.ForeignKey(Company) class Certification(models.Model): def increment_trial(self): last = Certification.objects.filter( package_id=self.package_id).order_by('trial').last() if not last: return 1 else: return last.trial + 1 date = models.DateField(auto_now_add=True) package = models.ForeignKey(Package, on_delete=models.CASCADE) trial = models.IntegerField(default=increment_trial(self)) note = models.TextField() I want some way of referencing the instance itself inside of the filter, or other way to reproduce the described behavior. PS: I barely speak english. -
Filter a Django queryset based on specific manytomany relationships
I have models similar to the Django documentation's pizza example: class Pizza(models.Model): name = models.CharField() toppings = models.ManyToManyField('Topping') def __str__(self): return self.name class Topping(models.Model): name = models.CharField() def __str__(self): return self.name And a few toppings with the expected pizzas: >>> pepperoni = Topping.objects.create(name='pepperoni') >>> sausage = Topping.objects.create(name='sausage') >>> pineapple = Topping.objects.create(name='pineapple') >>> olives = Topping.objects.create(name='olives') >>> ... How can I create a query that will return only return pizzas that have a topping of pepperoni, or sausage, or both pepperoni or sausage? Something like this will include a pizza that has pepperoni and olives, which I don't want: >>> Pizza.objects.filter(toppings__in=[pepperoni, sausage]) I can create a list of all toppings except the two I want and use that as an exclusion: >>> toppings_i_do_not_want = Topping.objects.exclude(name__in=['Pepperoni', ['Sausage']) >>> toppings_i_want = Topping.objects.filter(name__in=['Pepperoni', ['Sausage']) >>> Pizza.objects.filter(toppings__in=toppings_i_want).exclude(toppings_i_do_not_want) That will result in what I want, but it seems like the performance of such a query would suffer greatly if I'm only interested in two toppings but I have to pass ~100,000 other toppings into the exclude filter. Is there a better way? -
How to use django orm in a project without django
I have the following files in my project folder: database.db model.py: import os import sqlite3 from django.db import models class provincias(models.Model): key = models.AutoField(verbose_name="id",primary_key=True,unique=True) provincia = models.CharField(max_length=100) settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } but when executing django-admin migrate I get the following error: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. how can i do to use only the django orm connected to my sqlite3 database database bd -
Is the Django-cms addon, Aldryn news/blog; extensible?
I am using Django-cms to create a blog. In order to create the blog posts themselves, I am trying Aldryn news/blog. My question is, is there a way to add additional fields to the template for this particular addon? << Default news/blog template layout image >> What I am trying to do is to split each post into elements, which will be common across most/all posts for a given category. Then I could call each posts "elements" as such: {% if placeholder "contentElement_1" %} <some styling> {% placeholder "contentElement_1" %} </some styling> {% endif %} <some Style></> {% if placeholder "contentElement_2" %} <some styling> {% placeholder "contentElement_2" %} </some styling> {% endif %} <some Style></> etc... With this I have flexibility with regard to ad placement, accordions, cards and other styling within the html template, in and around the post elements. As I see it, with "Aldryn news/blog" I get one (% placeholder "content" %}, a title, and that's it. What Ive tried, future considerations: I'm assuming what I am looking for would create additional database fields for each "content element" as well. Which I would like for a later date to possibly be able to call for particular elements … -
Django Channels 2 - do I need to start a worker?
I've read where I only need to start a worker if somewhere in my code I use channel_layer.send(.... Is this correct? I thought the worker was the one handling all websocket requests. Please enlighten me. Thanks. -
django Filtering data from multiple tables having no foreign Key
model.py class Tas(models.Model): tas_id = models.AutoField(primary_key=True) date = models.DateTimeField(blank=True,null=True) ware_id = models.IntegerField(blank=True, null=True) taserid = models.CharField(max_length=100, blank=True, null=True) class Channels(models.Model): taserid = models.CharField(max_length=255, blank=True, null=True) type = models.CharField(max_length=255, blank=True, null=True) displayname = models.CharField(max_length=100, blank=True, null=True) class Ware(models.Model): ware_id = models.AutoField(primary_key=True) ware_name = models.CharField(null = False,max_length=255) taserid = models.CharField(null = True, max_length=255) views.py def index(request): assert isinstance(request,HttpRequest) display = Tas.objects.all(), cursor = connection.cursor() cursor.execute("select es.date,ew.ware_name,ec.type,ec.displayName from tas as es inner join ware as ew on ew.ware_id = es.ware_id inner join channels as ec on ec.taserId = es.taserId") I am facing problem in applying filters because there is no foreign key between Task,Channels,Ware. however there is a common field among these table.Please suggest how can i apply filter on the basis of Channels Table ---column type ,displayname and Tas Table--- column date -
Queryset question about base user model Django
Using the Django base User model. I'm getting a duplicate error using the base model pk. Not sure why my app can't seem to figure out which user is posting a comment. def view_api(request): user = request.user if request.method == 'POST': if request.user.is_active: price, created = Model.objects.get_or_create( user=User.objects.filter(pk=user.pk), anonymous_user=False, comments=request.POST.get('comments') ) Error: The QuerySet value for an exact lookup must be limited to one result using slicing. -
Using a function to create upload link of audio blob to send it to django server but not getting anything at sever end
I am using this function createDownloadLink which takes blob and create a download link to download the audio and also creates an upload link to upload the blob to the Django backend using xmlHttpRequest when I wrote a function in view to just see the blob data it is showing no POST data function createDownloadLink(blob) { var url = URL.createObjectURL(blob); var au = document.createElement('audio'); var li = document.createElement('li'); var link = document.createElement('a'); //name of .wav file to use during upload and download (without extendion) var filename = new Date().toISOString(); //add controls to the <audio> element au.controls = true; au.src = url; //save to disk link link.href = url; link.download = filename+".wav"; //download forces the browser to donwload the file using the filename link.innerHTML = "Save to disk"; //add the new audio element to li li.appendChild(au); //add the filename to the li li.appendChild(document.createTextNode(filename+".wav ")) //add the save to disk link to li li.appendChild(link); //upload link var upload = document.createElement('a'); upload.href="/show"; upload.innerHTML = "Upload"; upload.addEventListener("click", function(event){ let blob = new Blob(chunks, {type: media.type }); var xhr=new XMLHttpRequest(); xhr.onload=function(e) { if(this.readyState === 4) { console.log("Server returned: ",e.target.responseText); } }; var fd=new FormData(); fd.append("audio_data",blob, filename); //fd.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value')); xhr.open("POST","/show/",true); xhr.setRequestHeader('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value')); xhr.send(fd); }) … -
Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ projects/
when i running the server i m getting error as Page NOT Found these are the snippets of my code can anyone help me with this project urls.py from django.urls import path from . import views urlpatterns = [ path("", views.project_index, name="project_index"), path("<int:pk>/", views.project_detail, name="project_detail"), ] urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('projects/', include("projects.urls")), ] views.py from django.shortcuts import render from projects.models import Project def project_index(request): projects = Project.objects.all() context = {"projects": projects} return render(request, "project_index.html", context) def project_detail(request, pk): project = Project.objects.get(pk=pk) context = {"project": project} return render(request, "project_detail.html", context) models.py from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path="/img") -
register function does not show up after admin.site in my pycharm django development
I am supposed to use admin.site.register to register a model to my website, but register function does not show up after admin.site. There is a register function showing up after admin though. Should I use admin.regsiter instead of admin.site.register? from django.contrib import admin from .models import Question admin.site. (register does not show up) -
Django Views not cooperating on form submit
I have 3 buttons that should change the behavior of the videos on the page depending on the chosen dropdowns. But the user chooses a choice from the dropdown, the videos don't cooperate. This is the front end. When I choose something on for example language, the videos should change, but it doesn't. The page ends up on http://localhost:8000/?language=EN&level=LEV&category=CAT then the page breaks I tried adding a reverse_url on the views but it still didn't fix the error. def home(request): filter_form = AMLVideoFilterForm(request.GET) videos = AMLVideo.objects.all() category = filter_form.data.get('category') if category: videos = videos.filter( category__exact=category ) language = filter_form.data.get('language') if language: videos = videos.filter( language__exact=language ) level = filter_form.data.get('level') if level: videos = videos.filter( level__exact=level ) videos = videos.order_by("-category", "-language", "-level") context = {'videos': videos, 'filter_form': filter_form, 'level': level, 'language': language, 'category': category,} return render(request, 'home.html', context) The forms.py is: class AMLVideoFilterForm(forms.Form): LANGUAGE = [ ('LAN', 'Language'), ('EN', 'English'), ('FR', 'French'), ('HIN', 'Hindi'), ('SPA', 'Spanish'), ('GER', 'German'), ] LEVEL = [ ('LEV', 'Level'), ('BEG', 'Beginner'), ('INT', 'Intermediary'), ('ADV', 'Advanced'), ] CATEGORY = [ ('CAT', 'Category'), ('ADN', 'Adventure'), ('ANI', 'Animal'), ('ENV', 'Environmental'), ('MOR', 'Moral'), ('FOLK', 'Folktales'), ('POE', 'Poems'), ('FUN', 'Funny'), ] language = forms.ChoiceField( required=False, choices=LANGUAGE, widget=forms.Select( attrs={ 'onchange' : "this.form.submit()", … -
How to Send an Email Django
Previously, I was using SendGrid to serve emails using Django's SMTP backend, which worked perfectly fine. However, now I would like my project to use Microsoft Exchange. When I updated my SMTP configuration in settings.py, upon the submission of some form to be emailed, the page timesout when trying to reach the server: TimeoutError: [Errno 60] Operation timed out. settings.py # E-Mail EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.microsoft365.com' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_USE_TLS = True EMAIL_PORT = 587 views.py # Send email send_mail('!!New Mail!! ', content, 'noreply@domain.com', ['username@domain.com'], fail_silently=False) -
Django redirect with custom context
I am trying to send custom context in redirect request but the redirect is not working as I would like. it is redirecting me to a variable of the context instead. Here are my views def scenariopage(request,newContext): context = {} context.update(newContext) return render(request, 'scenariopage', context) def personforms(request): .... some forms code.... context = {'region':filled_form.cleaned_data['region'], 'industry':filled_form.cleaned_data['industry'], 'personUID':filled_form.cleaned_data['personUUID'], 'link': filled_form.cleaned_data['link'] } return scenariopage(request,context) This is the Terminal Debug output: [24/Sep/2019 16:10:54] "GET /scenario/2/ HTTP/1.1" 200 11616 [24/Sep/2019 16:10:57] "POST /personform HTTP/1.1" 200 7513 Not Found: /Retail [24/Sep/2019 16:10:57] "GET /Retail HTTP/1.1" 404 8631 Retailin this case is a variable contains in the context industry field. What am I doing wrong? -
Bootstrap Notify and Django Messages
How can I show error and warning Django messages using Bootstrap Notify? I'm using this template. I tried django-messages-to-bootstrap-notify but it's not working. I also used a HTML that I inspected from my browser: {% if messages %} {% for message in messages %} <div data-notify="container"><button type="button" aria-hidden="true" class="close" data-notify="dismiss" style="position: absolute; right: 10px; top: 5px; z-index: 1033;">×</button><span data-notify="icon"></span> <span data-notify="title"></span> <span data-notify="message">{{ message }}</span><a href="#" target="_blank" data-notify="url"></a></div> {% endfor %} {% endif %} This is a demo of the form. The author included a PHP code with the form and I think this is the part that shows the notification messages: if(!$mail->Send()) { $response = array ('response'=>'error', 'message'=> $mail->ErrorInfo); }else { $response = array ('response'=>'success'); } What's the best and easiest way to do this ? -
"Fields" not created with the sample polls apps mentioned in docs of django
I'm new to Django & am trying to create the polls app mentioned in the documentation section of django page. Followed exact steps mentioned & when the concerned code is executed, it says models are created but i don't see the field is added. Django version - 2.2.5 Python version - 3.6.4 python manage.py makemigrations polls as per docs, i should also see "- Add field question to choice" which is missing Expected: Migrations for 'polls': polls/migrations/0001_initial.py: - Create model Choice - Create model Question - Add field question to choice Actual: Migrations for 'polls': polls\migrations\0001_initial.py - Create model Question - Create model Choice -
Integrating Jumbo React template with Django
I am pretty new to React (and to frontend development, in general), and I am trying to integrate Jumbo React Admin template with Django. I have been able to launch Jumbo React Admin template on its own following this documentation, and I have, also, been able to integrate Django with React following this tutorial. The main difference between both tutorials (besides directory structure, that is not such a big issue) is that the first one is based in yarn, and the second one on webpack. I decided to use the official Jumbo documentation, and I am trying to do the integration using yarn. So far, I created a Django new project with a frontend application, and I copied Jumbo Admin template's directory in it. This is the resulting directories structure of the project: As you can see in the image, there is the following file: /Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/source/public/index.html but, any way, when I run yarn start, I get the following error: (JumboDjangoVenv) MacBook-Pro-de-Hugo:frontend hugovillalobos$ yarn start yarn run v1.17.3 $ react-scripts start Could not find a required file. Name: index.html Searched in: /Users/hugovillalobos/Documents/Code/JumboDjangoProject/JumboDjango/frontend/public error Command failed with exit code 1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command. I don't know how … -
Accounting for latency in simple multiplayer game?
At the moment, to account for latency, in my game (it is essentially tron lightcycles, but to move, one must solve a math problem), I send out the game state to both players every time one of the players turns. On the frontend, I have a function that draws and a function that undraws (to account for when there is latency). Currently, the setup is not performing the desired behavior: the players are not in sync with each other (neither movements nor positions at which users turn are the same for both players). Can someone help me out? This is my first time making a game. Here is the backend code (this code runs when a user submits an answer to a math problem in order to turn their character): def send_answer(answer, game_object, player_type, current_position, current_direction): creator_directions = ['p1up', 'p1right', 'p1down', 'p1left'] opponent_directions = ['p2up', 'p2right', 'p2down', 'p2left'] with transaction.atomic(): # d for direction if player_type == 'creator': for d in creator_directions: if is_correct_answer(getattr(game_object, d), int(answer)): context['move_direction'] = d print(context) new_problem = generate_problem_game( game_object.level, game_object.operation, game_object, player_type) setattr(game_object, d, new_problem) game_object.save() context['new_problem'] = [d, new_problem] # calculate draw and undraw positions # p1_last_pos: player 1 last position p1_last_pos = game_object.p1lastposupdate … -
How to activate virtual environment and start runserver by using .bat file with one click?
I m new to django. I got stuck while doing that, i found some resource but that didn't work for me. i have tried the command below, this start the chrome with localhost but i couldn't activate virtual environment along with run server. Anyone help me to do that, i want just one click to activate virtual environment and start server by using batch file. I m using windows @ECHO OFF start cmd.exe /C "python manage.py runserver && cd H:\djano-project\taskmate\ && D:" start C:\"Program Files (x86)"\Google\Chrome\Application\chrome.exe "http://127.0.0.1:8000/" -
How to add a user to django site, when using remote auth backend?
I am using Django for a site, and have a remote auth backend setup. Is there a way In which I can create a new user and give them permissions before they login to the site? I know I can add users through the admin page or directly through the database, but since I do not know the new users password, I am not sure if the system will see them as the same user I have tried using the admin page, but it says I need to enter a password I would like to be able to add users to the system before they logon, and give them permissions, so that when they logon they are not redirected to my unauthorized page. Is this possible? -
POST http://127.0.0.1:8000/ 401 (Unauthorized) using cors
I am working with django as backend and angular as fronted, using cors for the login, the thing is, when I try to make an insert in the backend from the fronted, it shows an error, this error POST http://127.0.0.1:8000/categoria 401 (Unauthorized) createCategoria(d: Categoria): Promise<Categoria> { return this.http .post("http://127.0.0.1:8000/categoria", JSON.stringify(d), { headers: this.headers }) .toPromise() .then(res => res.json() as Categoria) } the backend cors config and url config CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = [ "http://localhost:4200" ] url(r'^categoria$', views.CategoriaList.as_view()), url(r'^categoria(?P<pk>[0-9]+)$', views.CategoriaDetail.as_view()), POST http://127.0.0.1:8000/categoria 401 (Unauthorized) zone.js:2969 btw , the backend is running in 127.0.0.1:8000 -
The view blog.views.BlogViews didn't return an HttpResponse object. It returned None instead
I'm having a problem with the views for my blog main page. I've read a lot of problems with the same error but couldn't find a solution that i thought matched with my problem. I am trying to emulate my old code with a new View so that i can customise it further in the future. path('', ListView.as_view( queryset=Post.objects.filter(posted_date__lte=now).order_by("-posted_date")[:25], template_name="blog/blog.html")), i was previously using just the above url pattern to display my blog posts but im moving to a view: def BlogViews(TemplateView): def get(self, request): posts = Post.objects.all().order_by("-posted_date")[:25] args = { 'posts' : posts, } return render(request, 'blog/blog.html', args) and the new url path('', BlogViews, name='blog'), However this view is not working and returns the error in the title. I'm importing TemplateView, Post and render correctly i believe.