Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django createsuperuser not working due to TTY error
In django after populating the database, I started superuser creation but it fails and shows the error. Since I'm new to django and I cannot understand what is the error is about? python manage.py createsuperuser Error: Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually. -
I am building an educational website. CharField and TextField are unable to show proper mathematical symbols.What should i use?
Basically what the title says. Here is an example. ( i was not able to put an image as i don't have reputation of 10) [but imagine writing roots and polynomial equations on paper with proper exponents and root symbols rather than x^2 etc...] What can be done to achieve this? Thanks. -
ModelForm with user being request.user
I'm trying to make a form where user can submit a post/article. I have this model: class Post(models.Model): title = models.CharField(max_length=150) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) This form: class PostForm(forms.ModelForm): title = forms.CharField(required=True) content = forms.CharField(widget=forms.Textarea) class Meta: model = Post fields = ['title', 'content'] And this view: class PostCreateView(FormView): form_class = PostForm template_name = 'template/create_post.html' success_url = reverse_lazy('index') def form_valid(self, form): response = super(PostCreateView, self).form_valid(form) form.user = self.request.user form.save() return response I've set the user, but I'm still getting IntegrityError at /new-post/ NOT NULL constraint failed: cyth_post.user_id Here's the full traceback call: http://dpaste.com/0PJSTY2 What am I doing wrong here? Thanks in advance for answers! -
UI for Python and Django
I am new to Python and Django. I did my research before asking this question. I am using PyCharm as my IDE. Everyone is suggesting 1) Python + Django or 2) Angular + Nodejs I would like to learn Python, So I would like to go with Python. My Question is if I go with Python, Can I use Python + Angular 4. If so, what are the hurdles I am going to face? If I go with Python + Django, what are my options for UI(Bootstrap etc). Appreciate inputs and love to know industry standards. -
django channels: setting up async task
user clicks button on website relevant data for view as json object sent data sent to async view in django channel process starts counter = 0 for _ in range(1000000): #million as an example counter += 1 if counter%100 == 0: return json > {percentage, time_remaining} #result displayed on website, will figure out how the websocket will on browser will work #process complete return image path I have a process flow as the "code" above which I need to show the progress level. I've gone through the channels documentation, it's a lot and I'd rather ask than end up implementing the wrong way. -
Openssl version 1.0.2 is not compatible with docker - django
I have a django project that I am moving to docker. I am trying to run the project on my local machine on docker. I have loged into docker on my terminal and i am when i try to run the project, there is an issue with the openssl. can anyone help me figure out a version of openssl that will run on docker. This is what i am currently getting from my terminal.. λ docker build -t opentab-test . Sending build context to Docker daemon 2.093MB Step 1/6 : FROM python:3 ---> 968120d8cbe8 Step 2/6 : WORKDIR /usr/src/app ---> Using cache ---> f0bba915f632 Step 3/6 : COPY requirements.txt ./ ---> ee3dcb10168a Removing intermediate container 9776afaf8e9b Step 4/6 : RUN pip install --no-cache-dir -r requirements.txt ---> Running in b540798048a9 Collecting Django==1.11.2 (from -r requirements.txt (line 1)) Downloading Django-1.11.2-py2.py3-none-any.whl (6.9MB) Collecting olefile==0.44 (from -r requirements.txt (line 2)) Downloading olefile-0.44.zip (74kB) Collecting openssl==1.0.20 (from -r requirements.txt (line 3)) Could not find a version that satisfies the requirement openssl==1.0.20 (from -r requirements.txt (line 3)) (from versions: ) No matching distribution found for openssl==1.0.20 (from -r requirements.txt (line 3)) The command '/bin/sh -c pip install --no-cache-dir -r requirements.txt' returned a non-zero code: 1 does … -
nginx ignores view permissions when serving media files from django
I have the following setup: babl_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///tmp/babl.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name .example.com; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 75M; # adjust to taste # Django media location /media { internal; root /Users/haldunanil/Desktop/babl/backend; # your Django project's media files - amend as required } location /static { root /Users/haldunanil/Desktop/babl/backend; # your Django project's static files - amend as required } # Finally, send all non-media requests to the Django server. location / { uwsgi_pass django; include /Users/haldunanil/Desktop/babl/backend/backend/uwsgi_params; # the uwsgi_params file you installed } } directmessages/urls.py from django.conf.urls import url from directmessages.views import message_image_serve urlpatterns = [ url(r'^message_images/user_(?P<user1_id>\d+)/user_(?P<user2_id>\d+)/(?P<uuid>[0-9a-f-]+).jpg$', message_image_serve, name='message_image_service'), ] with the root url.py like this: url(r'^media/', include('directmessages.urls')), directmessages/views.py @api_view(['GET']) @permission_classes((IsAuthenticated,)) def message_image_serve(request, user1_id, user2_id, uuid): user_id = request.user.id if not user_id in (int(user1_id), int(user2_id)): raise Http404 path = 'message_images/user_%s/user_%s/%s.jpg' % (user1_id, user2_id, uuid) response = … -
create and save a csv file from html input element states to django model
On the frontend, I have a set of html input elements such as checkboxes and a button to create a new entry in a django model: user_detail.html main template <div class="col-md-4"> <h4><em>settings : </em></br></br></h4> <label class="input-toggle"> <input type="checkbox" id="A" unchecked onchange=""> <span></span> </label> <em>&nbsp A</em></br></br> <label class="input-toggle"> <input type="checkbox" id="B" unchecked onchange=""> <span></span> </label> <em>&nbsp B</em></br></br> <label class="input-toggle"> <input type="checkbox" id="C" unchecked onchange=""> <span></span> </label> <em>&nbsp C</em></br></br> <label class="input-toggle"> <input type="checkbox" id="D" unchecked onchange=""> <span></span> </label> <em>&nbsp D</em></br></br> </div> <a type="button" class="btn btn-outline-light btn-circle" href="{% url 'login_app:setting_new' %}" onclick=""><i class="glyphicon glyphicon-ok"></i></a> {% block upload_new_setting %} {% endblock %} urls url(r'^newsetting/$',views.UserSettingCreateView.as_view(),name='setting_new'), views class UserSettingCreateView(CreateView): fields = ('file',) model = models.UserSetting def get_success_url(self): return reverse('login_app:user_detail', kwargs={'pk': self.object.user.pk}) forms class UploadSettingForm(forms.ModelForm): class Meta(): """Method Description """ model = UserSetting fields = ('file',) models class UserSetting(models.Model): user = models.ForeignKey(User, related_name = 'usersetting') file = models.FileField(upload_to = 'settings', blank = True) def __str__(self): baselabel = self.file.name.split("S-")[1] index = baselabel.split("_")[0] date = baselabel.split("_")[1].split(".")[0] return("Setting N°: {} | Saved time : {}".format(index,date)) def get_absolute_url(self): return reverse("login_app:user_detail",kwargs={'pk':self.pk}) @property def setting_url(self): if self.file and hasattr(self.file, 'url'): return self.file.url and the html form block {% extends "login_app/user_detail.html" %} {% block upload_new_setting %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p … -
python django 404 error
i am learning python django.but i am getting this error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in x.urls, Django tried these URL patterns, in this order: ^admin/ ^y/ 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 a standard 404 page. i really don't know why i am getting this error first i created django project like: django-admin startproject x then i got these files: db.sqlite3 manage.py x then i created app like: python manage.py startapp y then i got these files: db.sqlite3 manage.py x y then i edited urls.py in my x folder and included the file that i created in y folder the code is my urls.py file in x folder from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^y/',include('y.urls')) ] my urls.py file in y folder from django.conf.urls import url from . import views urlpatterns = [ url(r'^$/', views.index, name = 'index'), ] my view.py file from folder y is from django.http import HttpResponse def index(request): return HttpResponse("<h1>hello sir</h1>") when i … -
Bottle vs Django
import bottle comes with wsgiref based http server(wsgi enabled) and provides web framework for routing and templating. With bottle, we do not need separate wsgi server & http server Apart from Django being a web framework, does it come with its own wsgi enabled http server? Or For using Django, Do we need separate wsgi server working with webser server? -
Adding an object to a specific foreign key using CreateView django
From my views: class SongCreate(CreateView): model = Song fields = ['album', 'name'] My functionality of adding a song (this) to an album is inside the details template of an album A. However, I want the input only be the name and not the album anymore since the song's album should automatically be "A." How do I make the code above behave such? From my urls: url(r'album/(?P<pk>[0-9]+)/song/add/$', views.SongCreate.as_view(), name='song-add') -
Sending Primary Key of object via Ajax
How to send primary key(pk) of the SELECTED object via AJAX. I tried {{pk}}, but unsuccessful. I am getting an error "Uncaught error" unexpected token} {% extends 'homepage.html' %} {% load staticfiles %} {% block teacher_diary %} <script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#grade_list').change(function(){ var element = document.getElementById("grade_list"); var value = element.options[element.selectedIndex].value; $.ajax({ url: "get_subject/", type: "get", data: { 'grade_id': value.{{ pk }} }, dataType: "json" }); })}); </script> <select id="grade_list"> {% for grade in grades %} <option >{{ grade }}</option> {% endfor %} </select> -
Add Import Button in Django Admin HomePage to import file from my Computer
I am working on Django project, what I want to do is add an 'Import' button in the Home>myApp (see pic below) that does the following: when you click on it, it display the file chooser, to choose a txt file from my computer. then call a function defined in views.py (example, readFile(filename)) to perform some action on that file. See this picture for more detail Any help is appreciated. -
Change default faker locale in factory_boy
How can I set the default localte in Python's factory_boy for all of my Factories? In docs says that one should set it with factory.Faker.override_default_locale but that does nothing to my fakers... import factory from app.models import Example from custom_fakers import CustomFakers # I use custom fakers, this indeed are added factory.Faker.add_provider(CustomFakers) # But not default locales factory.Faker.override_default_locale('es_ES') class ExampleFactory(factory.django.DjangoModelFactory): class Meta: model = Example name = factory.Faker('first_name') >>> from example import ExampleFactory >>> e1 = ExampleFactory() >>> e1.name >>> u'Chad' -
Why isn't my custom management command recognised?
I have made a custom management command "send_daily_report". It just aggregates a few usage statistics, and sends an email. My intent is for it to be called by cron each day. The command looks like this (simplified example): from django.template.loader import render_to_string from django.contrib.auth.models import User from django.core.mail import EmailMessage from my_app.models import Widget from datetime import datetime, timedelta from django.core.management.base import BaseCommand class Command(BaseCommand): commands = ['send_daily_report',] help = 'Daily activity report' def handle(self, *args, **options): context = [] context['new_widgets'] = Widgets.objects\ .filter(date_created__gt=(datetime.now() - timedelta(1)) )\ .count() text_body = render_to_string('daily_activity_report.txt', context) email = EmailMessage( subject="Daily report", body=text_body, from_email='noreply@example.com', to=[u.email for u in User.objects.filter(is_staff=True)] ) email.send(fail_silently=True) This is in /my_project/management/commands/send_daily_report.py as per the docs. I have an __init__.py in each directory, and a pycache with pyc files indicating that the file compiles. I'm using Python 3, Django 1.11. manage.py check reports no errors. Running manage.py send_daily_report gives me: Unknown command: 'send_daily_report'. In the shell, I can do: >>> from my_project.management.commands.send_daily_report import Command What's causing the management command not to be recognised? -
Django Custom Authentication class except wont return statement
check this out in backend file , i have authenticate method which return's the error associated with check password condition in if/else sucessfully , but it wont return the statement under except , instead it return error : ("You have multiple authentication backends configured and therefore must provide the backend argument or set the backend attribute on the user.") AUTHENTICATION_BACKENDS = ( 'games.backend.EmailorUsernameAuthBackend', 'django.contrib.auth.backends.RemoteUserBackend', 'django.contrib.auth.backends.ModelBackend', ) My custom backend class file stored in backend.py in my app directory from django.contrib.auth import get_user_model from django.core.exceptions import ObjectDoesNotExist class EmailorUsernameAuthBackend: def authenticate(self, username=None, password=None,errors=[]): if '@' in username: kwargs = {'email': username} else: kwargs = {'username': username} userobj = get_user_model() try: user = userobj.objects.get(**kwargs) if user.check_password(password): return user else: errors.append('password is wrong') except ObjectDoesNotExist: errors.append('no user found but you should love jesus!') Check my view which calls custom authenticate backend. def loginview(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] errors = [] if errors: return render(request, 'polls/accounts/login.html', {'errors': errors}) user = authenticate(request, username=username, password=password, errors=errors) login(request, user) return redirect('polls:index') return render(request, 'polls/accounts/login.html') -
Django CreateView/UpdateView with OnetoOne field depending if the record exists
I'm trying to build a profile page, where a User can fill in the Teacher model. My Teacher model, model.py class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='Teacher') rate = models.CharField(max_length=200) availability = models.BooleanField(default=False) forms.py class TeacherCreate(CreateView): user_id = request.user.id #INCORRECT! Needs something to remember current user id. model = Teacher fields = ['rate','availability'] We don't allow the user to change his ID in this create view. In fact, I believe this should be the current users id, user_id which is given by request.user.id. teacher_form.html <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form-group"> <span color="red">{{ field.errors }}</span> <label> {{ field.label_tag }} </label> <div>{{ field }}</div> </div> {% endfor %} <button type="submit">Submit</button> </form> Now the problem is that when I run it, I get the error: NOT NULL constraint failed: users_teacher.user_id which I believe is because I didn't specify the user_id. How I'd like it to work: First, check if the teacher already has a record in the database. E.G. if there is a row in the Teacher table, with user_id=current user. If the teacher has a profile -> Call the update view. If the teacher doesn't have a profile -> Use create view. -
MySQL syntax error after importing from local database django
I've developed my site and database using local server and local installation of mysql. now I've currently setup a actual server and now that I wanted to export my local database and imported via phpmyadmin I give this error: SQL query: CREATE TABLE `account_emailconfirmation` ( `id` int(11) NOT NULL AUTO_INCREMENT, `created` datetime(6) NOT NULL, `sent` datetime(6) DEFAULT NULL, `key` varchar(64) NOT NULL, `email_address_id` int(11) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `key` (`key`), KEY `account_ema_email_address_id_5b7f8c58_fk_account_emailaddress_id` (`email_address_id`), CONSTRAINT `account_ema_email_address_id_5b7f8c58_fk_account_emailaddress_id` FOREIGN KEY (`email_address_id`) REFERENCES `account_emailaddress` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; MySQL said: Documentation #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(6) NOT NULL, `sent` datetime(6) DEFAULT NULL, `key` varchar(64) NOT NULL,' at line 3 what is wrong? I tried to exclude this particular table but i had same error for some of other tables too. versions: mysql local: 5.7 mysql on web: 5.5 -
Django Multi Checkbox form
There has to be a better way to write this code. Basically, i have a list of emails in my database. I'm struggling to make a neat form, that will have separated emails checkboxes by year and by type. For example First year students Checkbox Checkbox Second year students: ....... My model looks like this class Email(models.Model): name = models.CharField(max_length = 254) email = models.EmailField(unique = True) year = models.IntegerField(default=0 course = models.IntegerField(default=0) type = models.CharField(max_length = 100) And the only way currently i managed to do this by writing many forms like this class Emailform1(forms.Form): my_models = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=None) def __init__(self, *args, **kwargs): super(Emailform1, self).__init__(*args, **kwargs) self.fields['my_models'].queryset = Email.objects.filter(course = 1).filter(type="Type") But this makes a big hassle working with a ton of forms in the view and etc.. -
Django Pydocs / reading the Django Documentation
since the Django online documentation only provides code examples, and doesn't really provide a simple module / class reference, I'm trying to read the pydocs locally but keep running into this problem. pydoc django error message I'm running the pydoc3 -p local server to browse the documentation. Why is it generating this error? Thanks for the Help. -
Sending email from Django using an email template
I have a pretty "contact form" template that I haven't written myself (snippet from a blog), but the form calls for a PHP script. Since I am just learning Django/Python, I wouldn't want to start fiddling with PHP just yet. What would I need to do to make the form work? HTML form: <form id="ajax-contact" method="post" action="contact-form-mail.php" role="form"> <div class="messages" id="form-messages"></div> <div class="form-group"> <label for="form_name">Name</label> <input id="form_name" type="text" name="name" class="form-control" placeholder="name"> <div class="help-block with-errors"></div> </div> <div class="form-group"> <label for="form_email">Email</label> <input id="form_email" type="email" name="email" class="form-control" placeholder="email" required="required" data-error="Valid email is required."> <div class="help-block with-errors"></div> </div> <div class="form-group"> <label for="form_message">Message</label> <textarea id="form_message" name="message" class="form-control" placeholder="Message" rows="4" required="required" data-error="leave a message."></textarea> <div class="help-block with-errors"></div> </div> <input type="submit" class="btn btn-light" value="Send message"> <br> <small class="text-muted"><strong>*</strong> These fields are required.</small> </form> I've set up SMTP settings as follows in settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'myemail@gmail.com' SERVER_EMAIL = 'myemail@gmail.com' -
Django, Nginx and Postgresql - Internal Server Error
I have a Django project, where I initially used Sqlite3 database, configured with Nginx and uWSGI on Digital Ocean droplet. With Sqlite3 database it works just perfect, but whenever I switch to PostgreSQL database (I have one on my server, and decided to use ORM instead of raw SQL, so I had to connect Django to it), I get "INTERNAL SERVER ERROR". What is really strange, is that it's still works with PostgreSQL and Django Development Server, and it works even if I launch uwsgi directly with uwsgi —http :8000 —module mysite.wsgi, but Nginx always gives me "INTERNAL SERVER ERROR". The only thing I change is DATABASES setting - to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } } from: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Forgot to mention that there is no any mistakes in nginx error log. -
Get all ManyToManyFields and ForeignKeys
I'm new in Django, this below are my classes, it's so that my Script has attributes for it self and globalattributes for all scripts. My Question is now how I can ask to get all my attributes for my script. so how to get all ManyToManyFields from GlobalAttribute for this Script and all ForeignKey from Attribute for this Script models.py from django.db import models class GlobalAttribute(models.Model): GlobalAttributename = models.CharField(max_length=256) GlobalAttributevalue = models.CharField(max_length=2048) def __str__(self): return self.GlobalAttributename class Script(models.Model): Scriptname = models.CharField(max_length=256) Description = models.CharField(max_length=512) Owner = models.CharField(max_length=128) GlobalAttribute = models.ManyToManyField(GlobalAttribute) def __str__(self): return self.Scriptname class Attribute(models.Model): Script = models.ForeignKey(Script, on_delete=models.CASCADE) Attributename = models.CharField(max_length=256) Attributevalue = models.CharField(max_length=2048) def __str__(self): return self.Attributename I know my question is dumb. -
Can I have a Django view that doesn't return a response?
Is it possible to have a Django view not return anything? Not any kind of HTTP error, data, or HTTP response (not even an empty 200 OK). Context: I have a view coded so that it's rate-limited. The code works well. A user can only trigger that view 5 times in any given minute; any more, and the user gets a 403 FORBIDDEN response. Instead of that, I want to be able to give no response at all. Not even an acknowledgement that the request was received and processed by Django. But as far as I know, views must return some kind of HTTP response. In fact I get an error if I just put a dry return in the view. Is it possible to do this? Thank you. -
Django Query Get Last Record with a Group By
I am trying to get all the last records based on the id, sorted my the month. this gives me the last record, qs = Cashflow.objects.filter ( acct_id = a.id ).order_by('-month')[:1] And this groups the accounts, qs = Cashflow.objects .filter ( acct_id = a.id ) .values ( 'acct_id' ) .annotate ( count = Count ( 'acct_id' ) ) .values ( 'acct_id', 'count' ) .order_by ( ) How how can I combine the two queries into one? Group by acct_id, sort by "month" and get last record. is this even possible? thanks