Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get HTML textbox context from django views.py?
I'm completely new in web development. I want to take the content from textbox then i'll process it in views.py. I'm trying to take id=anahtarkelime and id=url textbox values in Sonuc function when i click to id=search button. Current code: HTML file <form action="" method="post">{% csrf_token %} <label for="anahtarkelime">Anahtar Kelime</label> <input type="text" id= "anahtarkelime" name="anahtarkelime"> <label for="url">Aranacak URL</label> <input type="text" id= "url" name="url"> <br><br> <input id="search" type="button" value="ARA" /> </form> views.py def Sonuc(request): if(request.method == 'POST') and request.is_ajax(): word = request.POST['word'] url = request.POST['url'] print(word + ", " + url) data = { 'word': word, 'url': url} return HttpResponse(data) else: return render(request, 'html_files/Sonuc1.html') JS file $(document).ready(function(){ $("#search").click(function(){ $.ajax({ type: "POST", url: "/Sonuc/", data: { 'word': $('#anahtarkelime').val(), 'url': $('#url').val(), } }); }); }); -
using select2 in django admin search
I am trying to use select2 in the admin search. I'm sure it's useful to many because select2 allows us to search for a value without retrieving all the possible choices. First, I created a filter and have no choices loaded in it. Then, I overrode the admin template adding the following: <script src="{% static "autocomplete_light/vendor/select2/dist/js/select2.full.js" %}"></script> <link rel="stylesheet" href="{% static "autocomplete_light/vendor/select2/dist/css/select2.css" %}" /> <script> $(function(){ $("select[data-name='sample']").attr('class', 'select2_samples auto-width search-filter'); $(".select2_samples").select2({ placeholder: 'sample', ajax: { url: "/sample-autocomplete/", dataType: 'json', delay: 250, data: function (params) { return { q: params.term, // search term page: params.page }; }, cache: true }, escapeMarkup: function (markup) { return markup; }, // let our custom formatter work minimumInputLength: 0 }); }) </script> I even compared the search for of the admin change_list before and after. They look the same except an span tag is added after the select. Does anyone have any ideas why it does not work? I tried running this $('#changelist-search').serialize() in the browser console and it outputs: "q=" which means it is not registering my changes. Any ideas why it is not? -
Creating django form for related models
I have the following models defined: class Question(models.Model): date_added = models.DateTimeField(auto_now_add=True) question = models.CharField(max_length=200) number_of_answers = models.IntegerField(default=0) class Answer(models.Model): question = models.ForeignKey(Question) answer = models.CharField(max_length=200) votes = models.IntegerField(default=0) I want the user to be able to create a question along with its corresponding answers. Basically, I want to create a form that will ask the user to enter a question and the number of answers for the question. Based on the number-of-answers specified, I want to then create that many text fields for each answer. I want to be able to connect each answer to its corresponding question in the database. What is the best way to do this in Python Django? I have provided images of what this would look like visually. Getting question and number of answers, getting answers based on question and number of answers specified -
GitLab CI Django and Postgres
I am having an issue getting GitLab's CI to work with my Django project. I am using a postgres server and it appears I have set something up wrong. Any help would be much appreciated! The error: django.db.utils.OperationalError: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? My .gitlab-ci.yml file: image: python:3.6.1 services: - postgres:9.3 variables: POSTGRES_DB: project_ci_test POSTGRES_USER: postgres POSTGRES_PASSWORD: "" test: script: - export DATABASE_URL=postgres://postgres:@postgres:5432/project_ci_test - apt-get update -qy - apt-get install -y python-dev python-pip - pip install -r requirements.txt - python manage.py makemigrations - python manage.py migrate - python manage.py test Project In my django settings file: DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.postgresql_psycopg2', 'NAME' : 'project_ci_test', 'USER' : 'postgres', 'PASSWORD': '', } } I am currently trying to utilize GitLab's shared runners. I am hoping someone has successfully gotten a Django project with postgres to work on GitLab's CI. Thanks! -
Django factories for unit test: "Cannot assign "'1'": "User.group" must be a "Brand" instance."
I'm getting an error when I run my unit test for my user_profile/model.py: "Cannot assign "'1'": "User.group" must be a "Brand" instance." I believe this error is because, in my factories for my unit test (factories.py), I'm not correctly assigning group when I'm creating an instance of UserFactory(). I thing group should map to the Brand class/factory but I'm not sure how to do this.. this is my user_profile/model.py: class Brand(models.Model): name = models.CharField(max_length=20) def __unicode__(self): return self.name class User(AbstractBaseUser, PermissionsMixin): username = models.CharField( 'username', max_length=50, unique=True, db_index=True ) email = models.EmailField('email address', unique=True) group = models.ForeignKey(Brand, null=True, blank=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_approved = models.BooleanField(default=True) and in my user_profile/test/factories.py: from user_profile.models import User, Brand class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User django_get_or_create = ( 'username', 'email', 'password', 'is_approved', 'is_active', 'is_staff', 'is_admin', 'group' ) class BrandFactory(factory.django.DjangoModelFactory): class Meta: model = Brand django_get_or_create = ('name',) BrandFactory(name='BRAND1') BrandFactory(name='BRAND2') BrandFactory(name='BRAND3') BrandFactory(name='BRAND4') UserFactory( username='myuser1@gmail.com', email='myuser1@gmail.com', password=12345, is_approved=True, is_active=True, is_staff=True, is_admin=True, group="1" <--- HOW DO I MAP THIS TO THE 'BRAND1' FACTORY/CLASS?! ) UserFactory( username='myuser2@gmail.com', email='myuser2@gmail.com', password=12345, is_approved=True, is_active=True, is_staff=True, is_admin=True, group="2" <--- HOW DO I MAP THIS TO THE 'BRAND2' FACTORY/CLASS?! ) -
Python WebSocket Client connecting but not sending messages
While using websocket client to send test messages to a django server, I cannot get a script to work which can both send and receive messages. The following python script is what I have attempted: import websocket import threading import json from time import sleep # handle message event def on_message(ws, message): print("message recieved: %s" % message) # handle close event def on_close(ws): print("channel closed") # execute as main script if __name__ == "__main__": websocket.enableTrace(True) # new app object connecting to headstation ws = websocket.WebSocketApp("ws://192.168.0.106:8000/?testI123", on_message = on_message, on_close = on_close) # run in a new thread - kill if script ends ws_listener = threading.Thread(target=ws.run_forever()) ws_listener.daemon = True # start second thread ws_listener.start() # attempt connection 5 times timeout = 5 while not ws.sock.connected and timeout: sleep(1) timeout -= 1 # error on timeout if (timeout == 0): print("Connection to server timed out") print("test 1") # periodically send test message to server message_num = 0 while ws.sock.connected: # send node id and message message = 'hello %d'%message_num ws.send(message) sleep(1) message_num += 1 This connections successfully, indicted by the server, and receives messages sent from the server, but does not send anything. Periodically, something like this is displayed on the terminal: … -
Django keep track of object exports
I have my models in models.py with custom export method (that dumps my data to .xml file - in order to be included in .xml file company must have some fields manually filled in by me) class Country(models.Model): name = ... class Company(models.Model): country = ForeignKey(Country .. ) name = .... address = .... Companies are scraped from different sources and sometimes don't contain all the necessary information. Then I manually go through each company and I fill in the gaps. I need to somehow track how many companies I exported after clicking 'export button' for each country. I don't want to export multiple times the same company. My question is: How to approach this? Should I create a new class named Export where I will track everything or are there better methods? All the best and Merry Christmas! -
I am getting this invalid syntax error and I do not see error. Could someone help me locate the syntax error?
from django.urls import include, path from django.contrib import admin urlpatterns = [path('polls/', include('polls.urls')), path('admin/', admin.site.urls),] File "C:\Documents\Projects\mysite\polls\urls.py", line 1 This is line 1 ^ SyntaxError: invalid syntax -
Gunicorn giving me Module Not Found Error
I'm attempting to build a Django blog. I have a couple of apps in there, but for some reason Gunicorn is giving me trouble with - ` . ├── Procfile ├── blog │ ├── blog │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── settings.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── db.sqlite3 │ ├── manage.py │ ├── media │ │ ├── 1820-3-large.jpg │ │ ├── 1820-3-large_XGHcfcZ.jpg │ │ ├── 1820-3-large_ZTmLkYt.jpg │ │ ├── 1820-3-large_dPbPsPW.jpg │ │ └── paul-morris-144777.jpg │ ├── posts │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── admin.cpython-36.pyc │ │ │ ├── models.cpython-36.pyc │ │ │ └── views.cpython-36.pyc │ │ ├── admin.py │ │ ├── apps.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20171217_0000.py │ │ │ ├── __init__.py │ │ │ └── __pycache__ │ │ │ ├── 0001_initial.cpython-36.pyc │ │ │ ├── 0002_auto_20171217_0000.cpython-36.pyc │ │ │ └── __init__.cpython-36.pyc │ │ ├── models.py │ │ ├── static │ │ │ └── posts │ │ │ ├── css … -
Django-registration 'Password_reset_done' goes to the wrong URL route
On Djano-registration with Django 2.0 everything seems to be working OK. However, when I go to reset password, type in the email and submit, it redirects me to: http://127.0.0.1:8000/accounts/password/reset/auth_password_reset_done instead of: http://127.0.0.1:8000/accounts/password/reset/done/ It seems that it's confusing the url with the url name: ^accounts/ ^password/reset/done/$ [name='auth_password_reset_done'] Any ideas why? -
sitemap takes exactly 1 argument (0 given) in django 1.11
I tried to create a sitemap for my website using django's sitemap system. django version is 1.11.7 and I included both 'django.contrib.sitemaps' and 'django.contrib.sites' in settings.py file. urls.py file: from django.conf.urls import url, include from django.contrib import admin from django.contrib.sitemaps.views import sitemap from app.views import postSiteMap sitemaps = {'postMap':postSiteMap} urlpatterns = [ # other urls url(r'^sitemap.xml/$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap') ] sitemap view in views.py: def postSiteMap(Sitemap): changefreq = "daily" priority = 1.0 def items(self): return Post.objects.filter(is_draft=False) def lastmode(self, obj): return obj.postDate the error is : postSiteMap() takes exactly 1 argument (0 given) but i don't know where exactly I most add a argument. -
DJANGO: TemplateDoesNotExist: auth/user_confirm_delete.html
I'm trying to create a "delete account" functionality in Django. I use DeleteView for this purpose. The problem is that after calling this view, Django raises: Request Method: GET Request URL: http://127.0.0.1:8000/profiles/delete-account/ Django Version: 1.11.7 Exception Type: TemplateDoesNotExist Exception Value: auth/user_confirm_delete.html My view: class DeleteAccount(LoginRequiredMixin,DeleteView): model = User def get_object(self, queryset=None): user = self.request.user userprofile = user.userprofile userprofile.prepare_to_delete_account() return user Why it tries to render this template and why there is no such template if it's being called? Do you know how to fix this? -
In an DeleteView with the form, how does django know where to redirect to?
url.py url(r'^delete_student/,(?P<pk>\d+)/$' ,views.StudentDelete.as_view(), name='delete_student'), Error message: No URL to redirect to. Provide a success_url. Django Version: 1.9 Exception Type: ImproperlyConfigured Exception Value: No URL to redirect to. Provide a success_url. -
Django 2.0 reusable apps - TemplateDoesNotExist at /polls/
Python 3, Django 2.0 I just got to the end of the official Django tutorial, and I'm working on the advanced portion - "How to write reusable apps" It seems like I was at least partially successful, I can access the Questions and Choices through the admin interface, but when I try to display the http://127.0.0.1:8000/polls/ I get this error: TemplateDoesNotExist at /polls/1/ I get a similar error for trying to access a detail page, at http://127.0.0.1:8000/polls/1/ I looked through all the troubleshooting questions I could, and my main question is - how can you access templates that are packaged into an app? The thing I see going wrong is that Django is trying to find the app templates inside the main project directories(ie: /tutorial/templates/polls/detail.html), but they should be "inside" the module I imported from pip. Are you actually supposed to package the templates into apps this way? I tried throwing the template files back into tutorial/templates/polls/ and it works just fine, but this goes against what I think should be "reuseability" because then the packaged app won't have it's own templates. The answers I was able to find seem to be more for older versions of Django, and used … -
Django: send context to 'base.html'
I have a nav bar item that is used to register/login. As, it's gonna be in different pages, I'm thinking of calling this form "once" for every page, in the 'base.html'. I've found about the 'context processor' (Django - How to make a variable available to all templates?), however, as I can see, it passess only a variable to all templates. For that, it uses a function like this one on the file: view.py: def categories_processor(request): categories = Category.objects.all() return {'categories': categories} However, I'm using Class Views in my views.py, and, generally, I do pass the 'request', 'url to be rendered', 'context'. Like this: view.py: class RegistroClienteView(View): def get(self, request): ls_tipos_de_documento = TipoDocumento.objects.values_list('id', 'nombre_corto') form = ClienteCreationForm() context = {'form': form, 'ls_tipos_de_documento': ls_tipos_de_documento} return render(request, 'app_cliente/frontend/ingreso.html', context) def post(self, request): ls_tipos_de_documento = TipoDocumento.objects.values_list('id', 'nombre_corto') form = ClienteCreationForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'app_cliente/frontend/ingreso.html', context) context = {'form': form, 'ls_tipos_de_documento': ls_tipos_de_documento} return render(request, 'app_cliente/frontend/ingreso.html', context) My question is what to return in the View? After following the steps for seetting up the 'context-processor.py', in this file, I have: Please, notice that I'm only returning the context from app_cliente.forms import ClienteCreationForm from django.views import View from nucleo.models.tipo_documento import … -
Django admin loads blank page
I'm writing my first Django project in Django 2.0. I have created an app named sharednotes The contents of sharednotes/models.py is from django.conf import settings from django.db import models from notes.models import Note User = settings.AUTH_USER_MODEL class Shared(models.Model): note = models.ForeignKey(Note, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) email = models.CharField(max_length=100, blank=True, null=True) can_write = models.BooleanField(default=False) can_delete = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.note.title Here the note instance can be shared with user instance or to the email if user is not available. I have registered this model in sharednotes/admin.py from django.contrib import admin from sharednotes.models import Shared admin.site.register(Shared) on browing http://example.com/admin/ it lists Shareds which links to http://example.com/admin/sharednotes/shared/ but when clicking on it loads a blank page with no item on it. There is not even any error message or warning printed in terminal console. Could not understand what is causing this error. -
How to create a "Quiz" model that has unknown number of options with one or more correct answers?
I am trying to make a model for a "Question/Quiz" . A question can have as many choices (Charfields) as user wants , and there can be one or many correct answers (out of those options) . How should I define this model? Question: Some long description. Choice 1 Choice 2 Choice 3 - Correct Ans Choice 4 - Correct Ans So far I came up with this but I think it is a bad design: class Question(models.Model): description = models.CharField('Description', max_length=300) correct_answer_id = models.UUIDField('answer_id', null=True) options = models.ManyToManyField(Answer) class Answer(models.Model): """ Answer's Model, which is used as the answer in Question Model """ text = models.CharField(max_length=128, verbose_name=u'Answer\'s text') ans_id = models.UUIDField(default=uuid.uuid1()) -
django 2.0 - url match everything
I am trying to set my django 2.0 project urlconf so that all URLs go to the same app, and within that app all URLs point to the same view. Seems really simple! Still, my intuition and looking for help on the Internet fails me. I am completely new to django, but have experience with programming in general. Here is what I tried: I have the main project project/url.py with the setting: urlpatterns = [ path('admin/', admin.site.urls), path('', include('main_app.urls')) #Pattern A ] And then in the main_app/url.py: urlpatterns = [ path(r'^.*$', views.index, name='index') #Pattern B ] but using the address even with an empty URL (just the domain name) gives me an error: Using the URLconf defined in project.urls, Django tried these URL patterns, in this order: admin/ ^.*$ [name='index'] The empty path didn't match any of these. Looking for help directed me to these places (among others): What is the python regex to match everything? the suggestion there is to put r'^' as Pattern A, but this didn't work for me. Django URL template match (everything except pattern) the suggestion there is to use r'^.*' as Pattern B, which is exactly what I used. I noticed in the web … -
Very elementary TypeError in Django
I'm following all of the instructions in this tutorial, time 2:26 https://www.youtube.com/watch?v=gqRLPx4ZeSw&t=3s and I cannot get the expected result. The TypeError I'm getting is raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). File: urls.py from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^posts/$', 'posts.views.post_home'), # url(r'^posts/$', '<appname>.views.post_home'), ] File: views.py from django.shortcuts import render from django.http import HttpResponse def post_home(request): return HttpResponse("<h1>Hello</h1>") And here are the relevant screenshots, however I cannot post them because the computer thinks that they're code. Because it thinks they're code when I hit cntrl k the screenshots go away, but if I do not hit cntrl k, then I cannot post the thread. -
Django views.py raises requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected
I want to retrieve an image using requests in a Django View but it keeps on throwing error while doing. python org_logo = requests.get("http://github.com/org.png?size=32") print(org_logo) In this case it throws: HTML responses requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) HTML page response ConnectionError at / ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.11.8 Exception Type: ConnectionError Exception Value: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) Exception Location: /usr/local/lib/python3.6/site-packages/requests/adapters.py in send, line 473 Python Executable: /usr/local/opt/python3/bin/python3.6 Python Version: 3.6.0 I think this has something to do with the library requests -
Memory leak using django channels, apscheduler, and google oauth2client
My code pulls data from Google Analytics every X seconds and pushes it to a WebSocket frontend via Django Channels. I'm using an apscheduler BackgroundScheduler to run the tick function on the specified interval. But when I run this, the memory usage grows at a pretty constant rate even if all I do is authorize the oauth API. Example code from consumers.py: from channels.sessions import channel_session from apscheduler.schedulers.background import BackgroundScheduler from oauth2client import transport from apiclient.discovery import build scheduler = BackgroundScheduler() def tick(group_id): user = GoogleUser.objects.all()[0] # gets DjangoORMStorage instance credentials = get_credentials(user).get() # THESE TWO LINES SEEM TO CAUSE THE MEMORY LEAK oauth_http = credentials.authorize(transport.get_http_object()) analytics = build('analytics', 'v3', http=oauth_http) @channel_session def ws_connect(message): # accept socket connection and add channel to group message.reply_channel.send({"accept": True}) # add channel to websocket channel group redis_group = Group(group_id, channel_layer=None) redis_group.add(message.reply_channel) # schedule job scheduler.add_job(tick, 'interval', id=slug, kwargs={ 'group_id': group_id, }, seconds=settings.INTERVAL) scheduler.start() -
Django Form ChoiceField set choices in View in Form initial
This is the form class Form(Models.Form): title = forms.ChoiceField() I need to set choice values in title field according to what i get in queryset, how can it be done?? def func(request): titles = Titel.objects.all() form = Form(initial={ "title": "???titles???"}) return render('template.html', locals()) -
Override Field attribute in Django Model
I have a problem. I'm trying to change the directory on which a file gets uploaded, using the upload_to attribute of a FileField, without success. The main issue is that I have defined a parent class, with a file attribute, and I want to change the directory on the child class. My models are defined in this way : class DocumentBase(models.Model): file = models.FileField(upload_to=get_filename) class Document(DocumentBase): file_type = models.CharField(max_size=150) I tried to overwrite the FileField in the child class, without success (I'm aware now that this is not possible.) I also tried the answers on this other question (that is very similar to my problem), without success. Could somebody help me with this? Thanks! -
How to retrieve value from one to one field tables in Django?
I have used two models and a django built in User model. class UserInfo(models.Model): user = models.OneToOneField(User) user_contact = models.CharField() age = models.IntegerField() class Review(models.Model): user = models.ForeignKey('exam.UserInfo') is_reviewed= models.BooleanField() The UserInfo field is one to one with the User model. User model have the 'username' field that I want to retrieve. But I can't get through how to get the username of those users who have is_reviewed field is 0. So far what I was trying but failed to retrieve: result=Review.objects.select_related('user_id__id').filter(is_reviewed=0) -
[Django]Import data into mysql from file
Let's explain my problem. I'm trying to import data from a file ( 3 columns) into my local mysql database. It contains 27442 rows. i use code below def import(file): base_dir= '/home/xxxxx/Desktop/' with open(os.path.join(base_dir, file), 'r') as f: for line in f.readlines(): line=line.split() #remove all useless space if len(line) >= 3: host.objects.create( hostaddress=line[0], hostname= line[1], comment=line[2] #' ' by default ) else: raise('Invalide format') Everything seem work properly but when i check the table after importation. i get less than the half of total row (11xxx). code for django model class host(models.Model): hostname= models.SlugField(max_length=50) hostaddress= models.GenericIPAddressField(primary_key=True) comment= models.CharField(max_length=100) i need a help. Sorry for my bad english. Thanks.