Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Interpreting Django style vs SQLAlchemy style
In SQLAlchemy ORM you do session.add(person); session.commit(). In Django you do person.save(). Is there an important difference between these? It seems like the Django style requires attaching the model object closely to the database, whereas the SQLAORM style does not. When working outside of SQLAlchemy or Django, what makes one of these styles a more appropriate choice? Specifically, when should I design a system to use session.add(person); session.commit() vs person.save()? -
How to save binary data into .wav audio file by using wave module in Python
First of all I am using Python2.7 So right now I have some binary data audio which is taken from web, and now I need to convert this binary data and save it into local storage. Simple solution can be: with open('audio2.wav', 'w') as f: f.write(data) # Where data is binary data But if we will notice mediainfo for this particular audio file then it will be: General Complete name : audio2.wav Format : OGG File size : 49.0 KiB Duration : 3s 966ms Overall bit rate : 101 Kbps Writing application : Mozilla58.0 Audio ID : 1838225608 (0x6D9118C8) Format : Opus Duration : 3s 966ms Channel(s) : 2 channels Channel positions : Front: L R Sampling rate : 44.1 KHz Compression mode : Lossy Writing library : libopus unknown And if we do mediainfo of some original .wav audio file then it will look something like this: General Complete name : woman1_wb.wav Format : Wave File size : 220 KiB Duration : 7s 40ms Overall bit rate mode : Constant Overall bit rate : 256 Kbps Audio Format : PCM Format settings, Endianness : Little Format settings, Sign : Signed Codec ID : 1 Duration : 7s 40ms Bit … -
Django 2.0 'name' is not a registered namespace
I've seen this error posted several times, but I can't find anyone using Django 2.0 and having the problem. The problem cropped up when I tried to nest one app inside another. The nested app (called "users") is meant to allow users to login and out. After putting that segment in, I'm getting the following error: Template error: In template C:\Users\arbit\Documents\python\learning_log\learning_logs\templates\learning_logs\base.html, error at line 6 'users' is not a registered namespace 1 : <p> 2 : <a href="{% url 'learning_logs:index' %}">Learning Log</a> 3 : <a href="{% url 'learning_logs:topics' %}">Topics</a> 4 : {% if user.is_authenticated %} 5 : Hello, {{ user.username }}. 6 : <a href=" {% url 'users:logout' %} ">log out</a> 7 : {% else %} 8 : <a href="{% url 'users:login' %}">log in</a> 9 : {% endif %} 10 : </p> 11 : 12 : {% block content %}{% endblock content %} 13 : Here's my root urls.py from django.urls import path, include from django.contrib import admin from . import views app_name = "learning_log" urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls')), path('', include('learning_logs.urls')), ] urlpatterns = [ # Home page path('', views.index, name='index'), # Show all topics path('topics/', views.topics, name='topics'), # Detail page for a single topic path('topics/<int:topic_id>/', views.topic, … -
clear transaction log in sqlite3 database
I am using Sqlite3 in my Django Project. Initially my database size was less than 1 MB. It's been more than a year since I put it on my production server. The size has now become 121 MB. using dump command I copied its content to a .sql file here are first few lines PRAGMA foreign_keys=OFF; BEGIN TRANSACTION; CREATE TABLE "django_migrations" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "app" varchar(255) NOT NULL, "name" varchar(255) NOT NULL, "applied" datetime NOT NULL); INSERT INTO "django_migrations" VALUES(1,'contenttypes','0001_initial','2016-06-11 18:12:58.547832'); INSERT INTO "django_migrations" VALUES(2,'auth','0001_initial','2016-06-11 18:12:58.792963'); INSERT INTO "django_migrations" VALUES(3,'admin','0001_initial','2016-06-11 18:12:59.049214'); INSERT INTO "django_migrations" VALUES(4,'contenttypes','0002_remove_content_type_name','2016-06-11 18:12:59.361764'); INSERT INTO "django_migrations" VALUES(5,'auth','0002_alter_permission_name_max_length','2016-06-11 18:12:59.613627'); INSERT INTO "django_migrations" VALUES(6,'auth','0003_alter_user_email_max_length','2016-06-11 18:12:59.802244'); INSERT INTO "django_migrations" VALUES(7,'auth','0004_alter_user_username_opts','2016-06-11 18:13:00.001846'); INSERT INTO "django_migrations" VALUES(8,'auth','0005_alter_user_last_login_null','2016-06-11 18:13:00.190468'); INSERT INTO "django_migrations" VALUES(9,'auth','0006_require_contenttypes_0002','2016-06-11 18:13:00.257173'); INSERT INTO "django_migrations" VALUES(10,'default','0001_initial','2016-06-11 18:13:00.554142'); INSERT INTO "django_migrations" VALUES(11,'default','0002_add_related_name','2016-06-11 18:13:00.834812'); INSERT INTO "django_migrations" VALUES(12,'default','0003_alter_email_max_length','2016-06-11 18:13:01.067028'); INSERT INTO "django_migrations" VALUES(13,'default','0004_auto_20160423_0400','2016-06-11 18:13:01.234154'); there are too many transaction statements here. I guess this is why the file size has increased. Also, I found out that most of the size is taken by django_session table which is around 70 MB. tried python manage.py clearsessions but the file size didn't reduce I know there is shrink command in sql server … -
Django 2.0 dynamically generate urlpatterns
I wrote this code which is dynamically generate urlpatterns from db. These urls has only one level path ( domain.com/something ) someapp/models.py class SomeModel(models.Model): pattern = models.CharField(max_length=50) name = models.CharField(max_length=50) text = models.CharField(max_length=50) someapp/apps.py class SomeAppConfig(AppConfig): name = 'someapp' def ready(self): from .models import SomeModel from .urls import urlpatterns from . import views urls_in_db = SomeModel.objects.all() for url_in_db in urls_in_db: urlpatterns.append(path(url_in_db.pattern, views.SpecialView.as_view(), name=url_in_db.name) someapp/views.py class SpecialView(generic.TemplateView): template_name = 'template/view_template.html' model = SomeModel def get_context_data(self, **kwargs): context = super(SpecialView, self).get_context_data(**kwargs) context['content'] = SomeModel.objects.get(pattern=self.request.path) return context So the question is: Is this solution antipattern ? And if yes, why ? Thanks -
Django: how to mock a user with FB privilegies
I need to check that the content of a template is loaded properly. However, I need a user that has Facebook integration. This is my view: def profile(request, user_id): """A user's public pledge settings.""" user = get_object_or_404(SocialUser, pk=user_id) # We only want to show profile pages for users with Facebook integration try: user.social_auth.get(provider='facebook') except (UserSocialAuth.DoesNotExist, UserSocialAuth.MultipleObjectsReturned): raise Http404(_('User does not exist')) events = ['A', 'B', 'C'] context = { 'APP_ID': settings.SOCIAL_AUTH_FACEBOOK_KEY, 'user': user, 'last_event': events[-1], } return render(request, 'pledges/profile/profile.html', context) I think that I should create a mock object associated with a UserSocialAuth object, so I can skip that exception. However, I am not sure how to make the database to return this mock object. I am also using pytest for testing, so this is what I have so far: import pytest from unittest import mock from django.test import Client from django.urls import reverse from social_django.models import UserSocialAuth from pledges.models import SocialUser TEST_USERNAME = 'testuser' TEST_PASSWORD = 'password123' TEST_EMAIL = 'testuser@example.com' @pytest.fixture() def create_social_user(): """Creates a social user""" user = mock.Mock(spec=SocialUser) return user @pytest.mark.django_db def test_everytime_bar_is_displayed_on_profile_page_when_non_logged_in( create_social_user): user = create_social_user # I am not sure how to make this user to be the user gotten from the database UserSocialAuth.objects.create(user=user, provider='facebook', … -
Django reverse foreign key in
Model: class Book: title = CharField() author = ForeignKey(Person, related_name='books') class Person: name = CharField() How do I select persons that has books from a certain set? For example, select all persons, that have ('A', 'B', 'C') as books (and possibly more), i.e. subset. -
Django views.py code fails to find media files
I am developing an application in django where my views.py file needs to find a get a file located in the media folder. The structure of my directory is as follows: app/app/views.py app/media/streams/input/audio.mp3 In my views.py I have the following code: filename = "../media/streams/input/audio.mp3" file = open(filename, "r") But when I run the function, I get the following error: [Errno 2] No such file or directory: ../media/streams/input/audio.mp3 I am not sure how to put the right path in it or is it something else that I need to do? -
Returning an image from a Django view using django-sslserver
I'm trying to return an image from a Django 1.11 view while using django-sslserver and Pillow. Here's a minimal view I made for testing. def get_image(request): img = Image.open('oh_noes_cat.png', mode='r') response = HttpResponse(content_type='image/png') img.save(response, 'png') return response In my template I use: <img src={% url "get_image" %} /> In urls.py, I use: url(r'^get_image.png', get_image, name='get_image') The image response works fine with Django runserver but fails under both django-sslserver and runserver_plus from django-extensions. What I see in Chrome is a broken image icon and the error "ERR_CONTENT_LENGTH_MISMATCH". When using django-sslserver I get the error: [26/Dec/2017 18:55:39] "GET /get_image.png HTTP/1.1" 200 0 Traceback (most recent call last): File "/usr/lib/python3.5/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.5/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib/python3.5/wsgiref/handlers.py", line 279, in write self._write(data) File "/usr/lib/python3.5/wsgiref/handlers.py", line 453, in _write result = self.stdout.write(data) File "/usr/lib/python3.5/socket.py", line 593, in write return self._sock.send(b) File "/usr/lib/python3.5/ssl.py", line 861, in send return self._sslobj.write(data) File "/usr/lib/python3.5/ssl.py", line 586, in write return self._sslobj.write(data) ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:1844) [26/Dec/2017 18:55:39] "GET /get_image.png HTTP/1.1" 500 59 Does anyone know how I can make an image response work with django-sslserver or a similar solution for supporting SSL in a Django development environment? I've … -
how to obtain lock on django model for concurrent Operation
i am trying to obtain locking in django model such as if user 1 is editing admin action will be disabled for user 2 once user 1 leaves the form user 2 will have access. but still not able to find solution -
Best way to make "viewed" attribute for messages inside user group?
I am deciding on how to track if a user has seen a post in the timeline or not. There is Post and Comment model like this. class Comment(models.Model): author = models.ForeignKey('UserProfile') title = models.CharField(max_length=255) text = models.TextField(null=True, blank=True) date_created = models.DateTimeField() post = models.ForeignKey('Post', related_name='comments') class Post(ContentTypeModel): title = models.CharField(max_length=255) group = models.ForeignKey('UserGroup', null=True) date_updated = models.DateTimeField() Suggestions about best practices on how to track if post has been seen by particular member of a user group will be nice. -
Built a bootstrap form and trying to use it in Django - Invalid data
My form was working fine when I used {{ form.as_p }} but when I decided to design my form using the twitter bootstrap and added widgets to my fields to be able to use the new form, I no longer receive the form submissions in a folder (because I'm using the send_mail function). It seems that the request is not entering the is_valid block and I can't really figure out why. Note: I'm trying to debug and I'm getting that the email field is required despite filling it with a genuine email. My form: from django import forms class ContactForm(forms.Form): first_name = forms.CharField(widget=forms.TextInput(attrs={'id': 'first_name'})) last_name = forms.CharField(widget=forms.TextInput(attrs={'id': 'last_name'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'id': 'email-address'})) message = forms.CharField(widget=forms.Textarea(attrs={'id': 'message'})) My view: from django.shortcuts import render from myblog import forms # To be able to send mail from django.contrib import messages from django.core.mail import send_mail from django.urls import reverse from django.http import HttpResponseRedirect def contact_form(request): form = forms.ContactForm() # If POST request is coming if request.method == 'POST': # Fills the form with the data form = forms.ContactForm(request.POST) # Check if the data is good if form.is_valid(): send_mail( 'Message from {} {}'.format(form.cleaned_data['first_name'], form.cleaned_data['last_name']), form.cleaned_data['message'], '{first_name} {last_name} <email>'.format(**form.cleaned_data), ['test@gmail.com'] ) # Send message messages.add_message(request, messages.SUCCESS, … -
How to change order field based on language selection?
I create a custom MultilingualCharField and I want order the instances by it, in the right language. I prefer to do so in the model, is it possible? class Myclass(models.Model): name = MultilingualCharField(max_length=32, unique=True) ... def __str__(self): name_traslated={'name_it': self.name_it, 'name_en': self.name_en} name_verbose=_('name_it') return name_traslated[name_verbose] class Meta: #name_traslated={'name_it': self.name_it, 'name_en': self.name_en} name_verbose=_('name_it') ordering = [name_verbose] #ordering = [name_traslated[name_verbose]] __str__ is working but ordering is not: it gives TypeError: 'class Meta' got invalid attribute(s): name_verbose My MultilingualCharField create two columns: name_it and name_en, here the code (from Web Development with Django Cookbook): class MultilingualCharField(models.CharField): def __init__(self, verbose_name=None, **kwargs): self._blank = kwargs.get("blank", False) self._editable = kwargs.get("editable", True) #super(MultilingualCharField, self).__init__(verbose_name, **kwargs) super().__init__(verbose_name, **kwargs) def contribute_to_class(self, cls, name, virtual_only=False): # generate language specific fields dynamically if not cls._meta.abstract: for lang_code, lang_name in settings.LANGUAGES: if lang_code == settings.LANGUAGE_CODE: _blank = self._blank else: _blank = True localized_field = models.CharField(string_concat( self.verbose_name, " (%s)" % lang_code), name=self.name, primary_key=self.primary_key, max_length=self.max_length, unique=self.unique, blank=_blank, null=False, # we ignore the null argument! db_index=self.db_index, rel=self.rel, default=self.default or "", editable=self._editable, serialize=self.serialize, choices=self.choices, help_text=self.help_text, db_column=None, db_tablespace=self.db_tablespace ) localized_field.contribute_to_class(cls, "%s_%s" % (name, lang_code),) def translated_value(self): language = get_language() val = self.__dict__["%s_%s" % (name, language)] if not val: val = self.__dict__["%s_%s" % (name, settings.LANGUAGE_CODE)] return val setattr(cls, name, … -
Django: smart-select how to use it in forms.py
I am using smart_selects in Django to filter drop down views. In my admin page, I was successful in doing this using 'ChainedForeignKey' I am now trying to create a user form and implement the same thing. my approach is models.py class LegalDocumentField(models.Model): name = models.CharField(max_length=255, default="default", verbose_name="Tên") desc = models.CharField(max_length=255, default="default", verbose_name="Chi tiết") def __unicode__(self): return self.name class Meta: verbose_name = 'Lĩnh vực văn bản pháp luật' verbose_name_plural = 'Lĩnh vực văn bản pháp luật' class LegalDocumentType(models.Model): linhvuc = models.ForeignKey(LegalDocumentField, on_delete=models.CASCADE, verbose_name="Lĩnh vực") name = models.CharField(max_length=255, default="default", verbose_name="Tên") desc = models.CharField(max_length=255, default="default", verbose_name="Chi tiết") def __unicode__(self): return self.name class Meta: verbose_name = 'Loại văn bản pháp luật' verbose_name_plural = 'Loại văn bản pháp luật' forms.py class LegalDocumentForm(forms.Form): document_field = ModelChoiceField(label=_("Lĩnh vực văn bản"), queryset=LegalDocumentField.objects.all(), empty_label="--Lĩnh vực văn bản--", required=False) #ag document_type = ChainedModelChoiceField( to_app_name="myapp", to_model_name="LegalDocumentType", chained_field="linhvuc", chained_model_field="linhvuc", foreign_key_app_name="myapp", foreign_key_model_name="LegalDocumentType", foreign_key_field_name="linhvuc", show_all=False,auto_choose=True) template.html ... <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script type="text/javascript" src="{% static '/smart-selects/admin/js/chainedfk.js' %}"></script> <script type="text/javascript" src="{% static '/smart-selects/admin/js/bindfields.js' %}"></script> ... <form role="form" action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> i want when someone selects document_field the document_type selections are filtered accordingly.But the document_type selections was empty when i changed document_field value. -
How to POST Django Inline Formset with images via AJAX
I'm trying to process inline formset with images via Ajax: forms.py class UserDogCreateForm(forms.ModelForm): class Meta: model = UserDog fields = ['name', 'breed', 'gender'] class UserDogImageCreateForm(forms.ModelForm): class Meta: model = UserDogImage fields = ['image', 'dog'] labels = {'image': ''} UserDogCreateFormSet = forms.inlineformset_factory( UserDog, UserDogImage, form=UserDogImageCreateForm, extra=3, can_delete=False, can_order=False, ) views.py class UserDogCreateView(LoginRequiredMixin, CreateView): model = UserDog form_class = UserDogCreateForm def get_context_data(self, **kwargs): context = super(UserDogCreateView, self).get_context_data(**kwargs) if self.request.POST: context['dog_image_inlines'] = UserDogCreateFormSet(self.request.POST, self.request.FILES) else: context['dog_image_inlines'] = UserDogCreateFormSet() return context def form_valid(self, form): context = self.get_context_data() inlines = context['dog_image_inlines'] with transaction.atomic(): if inlines.is_valid(): form.instance.user = self.request.user self.object = form.save() inlines.instance = self.object inlines.save() user_dogs = UserDog.objects.filter(user=self.request.user) return JsonResponse({'form_is_valid': True, 'user_dogs': serializers.serialize('json', user_dogs)}) else: return JsonResponse({'form_is_valid': False}) def form_invalid(self, form): return JsonResponse({'form_is_valid': False}) .html <form id="dog-create-form" enctype="multipart/form-data" action="{% url 'dog-create' %}" method="post"> {% csrf_token %} {{ form }} {{ dog_image_inlines.as_p }} <button type="submit">Submit</button> </form> .js var dogCreateForm = $('#dog-create-form'); dogCreateForm.submit(function(e){ e.preventDefault(); var data = new dogCreateForm.serialize(); console.log(data); $.ajax({ url: '/accounts/dog-create/', type: 'post', dataType: 'json', data: data, success: function(data) { if (data.form_is_valid) { console.log('Dog created!'); // <-- This is just a placeholder for now } else { console.log('Dog not created!') } }, }); }) After submit UserDog data saves, but no images saves in UserDogImage … -
Optimization of querys in django eliminating querys duplicates
I'm trying to get the number of products that have each category, but each category is in turn parent of other categories, so I want to know how many children have that category and their daughter categories, I have simplified the query to the maximum in the following way, but in the django debug I keep showing that I have 66 querys duplicates. How can I eliminate these duplications? With the first line of views.py, he managed to get the number of products in a category, but the problem is essentially to tell him to return me from the category and his daughters. models.py class Categoria(models.Model): nombre = models.CharField(max_length=200) slug = models.SlugField(max_length=100) padre = models.ForeignKey('self', blank=True, null=True, related_name='cat_padre') pub_date = models.DateTimeField('date published', auto_now_add=True) upd_date = models.DateTimeField('date updated', auto_now=True) def __str__(self): return self.nombre + ' ' + self.pais.iso class Producto(models.Model): nombre = models.CharField(max_length=200) slug = models.SlugField(max_length=100) categoria = models.ForeignKey(Categoria) views.py cats = Categoria.objects.annotate(num_productos=Count('producto')).filter(pais__iso=pais, padre__isnull=True).order_by('-num_productos') for c in cats: num_p = Producto.objects.filter(categoria__padre=c).count() c.num_productos += num_p contexto = { 'categorias_padre': cats, } return render(request, 'web/pruebitas/product.html', contexto) Django debug: SELECT COUNT(*) AS "__count" FROM "web_producto" INNER JOIN "web_categoria" ON ("web_producto"."categoria_id" = "web_categoria"."id") WHERE "web_categoria"."padre_id" = '790' Duplicated 62 times. Conexión: default /home/luis/PycharmProjects/lco_web/web/middleware.py in __call__(29) … -
JSON POST with cURL / libcurl function doesnt work
I have a Django Server which receives JSON Data via Post and also returns a JSON via response. I tested my Code with the CURL Command with the terminal of macOS and it works. The command is curl -H "Content-Type: application/json" -X POST -d '{"mac":"24:0a:c4:04:fd:28","battery":"100", "message":"You have a message"}' http://192.168.178.34:8000/kalender/returnjson/ Now I want my microcontroller to send the exact same Post like the curl-Command above. The function is written in C-language. int sendCurl(){ CURL *curl; CURLcode res; curl = curl_easy_init(); char* jsonObj = "{ \"mac\" : \"24:0a:c4:04:fd:28\" , \"battery\" : \"100\" , \"message\" : \"You got a message\"}"; struct curl_slist *headers = NULL; curl_slist_append(headers, "Accept: application/json"); curl_slist_append(headers, "Content-Type: application/json"); curl_slist_append(headers, "charsets: utf-8"); curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.178.34:8000/kalender/returnjson/"); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj); curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcrp/0.1"); res = curl_easy_perform(curl); curl_easy_cleanup(curl); curl_global_cleanup(); return res; } But my server doesnt get any incoming POST request. (my server does print outs when receiving something, but its not the case) What is wrong with the code written in C? -
Pass data from php to python and get result
I want to send data from php to python and make some computations. After that I want to send result of that. The problem is I cannot send data from php to python. python.php username is working but shell_exec or python have problem <?php if(isset($_POST["username"])){ $nick = $_POST["username"]; echo shell_exec("python new.py '$nick'"); $jsonData = $_POST["prediction" ]; echo $jsonData; } ?> new.py When I run python it prints C:\wamp\www\MLWebsite\website\new.py but it should be parameter import pymysql.cursors import sys import urllib2, urllib import requests x=sys.argv[0] print x I want to get some idea about sending result because end of new.py mydata=[('prediction','BIO')] mydata=urllib.urlencode(mydata) path='http://localhost/MLWebsite/website/python.php' #the url you want to POST to req=urllib2.Request(path, mydata) req.add_header("Content-type", "application/x-www-form-urlencoded") page=urllib2.urlopen(req).read() print page I use Firebug plugin in Firefox and this error is also shown in webpage. ( ! ) Notice: Undefined index: prediction in C:\wamp\www\MLWebsite\website\python.php on line 6 Call Stack #TimeMemoryFunctionLocation 10.0006245144{main}( )..\python.php:0 -
how can I avoid same account login at the same time in django
I use Django, DRF, and JWT.I want to avoid same account login in mobile App at the same time, mobile App and website can login at the same time. how can I do that? there is package can do this? -
Error during Pip Django Install
Yesterday, I installed Django on my aunt's pc and it worked wonders. Today, I'm trying to install it on my pc, and it gives the following error: Exception: Traceback (most recent call last): File "c:\program files\python36-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\program files\python36-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\program files\python36-32\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\program files\python36-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_f isolated=self.isolated, File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\program files\python36-32\lib\site-packages\pip\wheel.py", line 316, in clobber ensure_dir(destdir) File "c:\program files\python36-32\lib\site-packages\pip\utils\__init__.py", line 83, in ensure_dir os.makedirs(path) File "c:\program files\python36-32\lib\os.py", line 220, in makedirs mkdir(name, mode) PermissionError: [WinError 5] Acceso denegado: 'c:\\program files\\python36-32\\Lib\\site-packages\\pytz' I'm counting on you guys. I'm new to this world, and I'm willing to learn. P.D.: "Acceso denegado" = "Access denied" -
Where do Django model fields reside?
I've looked into the source code for some django model fields, in this case DateTimeField. In the tutorial for Django, we are taught to create a DateTimeField like this: from django.db import models field = models.DateTimeField() But looking in the source code, the file where DateTimeField is defined is django/db/models/fields. So, intuitively, if I were to import the field, I would write from django.db.models.fields import DateTimeField. Do you see the difference? In the tutorial, they import it from django/db/models, while it looks like from the location of the source code that it actually resides in django/db/models/fields. Why doesn't the tutorial way of importing DateTimeField crash? -
DJANGO_SETTINGS_MODULE not recognizing my base module when starting a new project with Virtualenvwrapper
I am starting a new Django project with virtualenvwrapper, and for some reason django-admin does not recognize my settings module: $ mkproject djangotest (djangotest) $ pip install Django Collecting Django Using cached Django-2.0-py3-none-any.whl Collecting pytz (from Django) Using cached pytz-2017.3-py2.py3-none-any.whl Installing collected packages: pytz, Django Successfully installed Django-2.0 pytz-2017.3 (djangotest) $ django-admin The above command works and gives me the menu of django-admin subcommands. However, when I try to set DJANGO_SETTINGS_MODULE, my new djangotest app is not recognized: (djangotest) $ cd ../ (djangotest) $ django-admin startproject djangotest (djangotest) $ cd djangotest (djangotest) $ ls djangotest manage.py (djangotest) $ export DJANGO_SETTINGS_MODULE=djangotest.settings (djangotest) $ django-admin Traceback (most recent call last): File "/Users/sam/Dropbox/.virtualenvs/djangotest/bin/django-admin", line 11, in <module> sys.exit(execute_from_command_line()) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/core/management/__init__.py", line 317, in execute settings.INSTALLED_APPS File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/site-packages/django/conf/__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/sam/Dropbox/.virtualenvs/djangotest/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 994, in _gcd_import File … -
How to refer multiple model object using one model field in django?
Suppose, I have Project and Manager model. class Project(models.Model): name = models.CharField(max_length=50) class Manager(models.Model): name = models.CharField(max_length=50) projects = This would be array of Project object. But how can I implement this? PostgreSQL has ArrayField for this implementation. But I want a solution that will work for any database. Any alternative solution would be highly appreciable. -
could not use custom templatetags in Django 2.0
I'm using Django 2.0. I have written few custom template tags to use in the template inside notes/templatetags/note_tags.py file where notes is app directory I have written few custom tags inside this file from django import template from django.template.defaultfilters import stringfilter from notepad.utils import simplify_text from notes.models import Note, ColorLabels register = template.Library() @register.filter(name='note_simplify') @stringfilter def note_simplify(value): return simplify_text(value) @register.filter(name='default_color_label') def default_color_label(): default_label = ColorLabels.objects.filter(default=True).first() print(default_label.value) return default_label and inside the template file, I have loaded the tag as {% load note_tags %} I'm able to use the first tag note_simplify but second tag default_color_label is not being called. I'm using both tags in the same file. One for modifying the passed data and another to simply print something # modify the note.content <p>{{ note.content|truncatechars:200|note_simplify }}</p> # to print some value {{ default_color_label.value }} I have also restared server many times. Is there something wrong? Why the tag is not being called in template? -
TypeError: object of type 'EmailMultiAlternatives' has no len()
Django app, sending an email using a script (using runscript), only on weekdays. Trying to use Google's STMP. Here's the relavent script: import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "labschedule.settings") django.setup() import datetime from datetime import date import smtplib from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from labschedule import settings def run(): today = date.today() subject = "Daily Report for %s" % today to = [settings.EMAIL_ADMIN] from_email = 'blahblah@gmail.com' # My email reservations = Event.objects.filter(day=today).order_by('cart') last = Event.objects.latest('day') if today >= today + datetime.timedelta(days=5): countdown = last - datetime.timedelta(today) warning = "Hey! You run out of open slots in %s days" % countdown else: warning = None ctx = ({ 'reservations' : reservations, 'warning' : warning, 'cart_choice' : cart_choice }) html_content = render_to_string('schedule/email.html', ctx) text_content = render_to_string('schedule/email.html', ctx) msg = EmailMultiAlternatives(subject, text_content, to=to, from_email=from_email) msg.attach_alternative(html_content, "text/html") weekend = set([5, 6]) # Python week starts on Monday as 0 if today.weekday() not in weekend and settings.DAILY_EMAIL == True: server = smtplib.SMTP_SSL('smtp.gmail.com', 465) server.ehlo() server.login(settings.gmail_user, settings.gmail_password) server.sendmail(from_email, to, msg) server.close() print ('Email sent!') else: pass I went mostly of the tutorial here. The error I receive: TypeError: object of type 'EmailMultiAlternatives' has no len() I'm newish, and I know it's something dumb, and would …