Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django multiprocessing Error: "AttributeError: Can't pickle local object 'Command.handle.<locals>.f'"
I'm using python 3.6 django 1.11 windows10 and trying to send email using multiprocessing. recipients are connected to database(django model) and email contents form is html(by django get_template), also used get_connection to send multi-email. What I'm trying is to use multiprocessing to accelerate sending rate. My code is here from django.core.management.base import BaseCommand from django.core.mail import get_connection, EmailMessage from django.template.loader import get_template from multiprocessing import Pool from sending.models import Subscriber class Command(BaseCommand): def handle(self, *args, **options): connection = get_connection() recipients = [i.email for i in Subscriber.objects.all()] num = Subscriber.objects.count() subject = 'Multiprocessing trying 1' body = get_template('Newsletter20171229.html').render() from_email = 'info@modoodoc.com' def send(i): msg = EmailMessage(subject, body, from_email, [recipients[i]]) msg.content_subtype = 'html' print("Sending email to: " + recipients[i] + " No: " + str(i)) connection.send_messages([msg]) print("Complete.") pool = Pool(processes=2) pool.map(send, range(0, num)) print("Mail have just sent. The program is going to end.") connection.close() And I've got an error like this. File "c:\python36-32\Lib\multiprocessing\connection.py", line 206, in send self._send_bytes(_ForkingPickler.dumps(obj)) File "c:\python36-32\Lib\multiprocessing\reduction.py", line 51, in dumps cls(buf, protocol).dump(obj) AttributeError: Can't pickle local object 'Command.handle.<locals>.f' How to fix this? Thank you. -
ValueError at /app/top/
I got an error, ValueError at /app/top/ The view app.views.top didn't return an HttpResponse object. It returned None instead. I wrote codes in views.py from .models import POST from django.shortcuts import render def top(request): contents = POST.objects.order_by('-created_at') render(request, 'top.html', {'contents': contents}) in models.py from django.db import models class POST(models.Model): title = models.CharField(max_length=100) text = models.TextField() in html <body> <div> {% for content in contents.all %} <div> <h2>{{ content.title }}</h2> <p>{{ content.text }}</p> </div> {% endfor %} </div> </body> In model, several data of title&text is registed,so surely data is not empty.I think this is directory mistake, now my application structure is -mysite(parent app) -app(child app) -templates -top.html -models.py -views.py so I do not know what is wrong.How should I fix this?What is wrong in my codes? -
Is there a way to view word files locally using office web viewer
I have a word file, and I want to open up that word file for preview/viewing purposes only, not to edit. How could I go by this? I have a Django application and one of the main purpose of the application is to view documents that people upload on the site. However for testing purposes I cannot get to preview documents for reasons I do not know. I am using Microsoft office viewer to view the files. This is my html code in Django: <iframe src="https://view.officeapps.live.com/op/embed.aspx?src=http://127.0.0.1:8000/media/project/1/f73ab109-dcaa-4cc3-bbfc-7121eca10118.doc"> </iframe> And this is was the error displayed in the html: I am assuming that the office viewer is expecting a "real" internet directory and not something locally. -
nginx 502 bad gateway: upstream prematurely closed connection while reading response header from upstream
I have a Django app with which users can create video collages using multiple videos. Problem is, on production, when uploading videos to amazon s3, I get a 502 bad gateway (works fine locally). Does anyone know what could be wrong? I already set client_max_body_size 100M and fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; fastcgi_connect_timeout 3000; fastcgi_send_timeout 3000; fastcgi_read_timeout 3000; Does anyone know what could be wrong? Thanks in advance -
How to enforce reads from read replica in Postgres using django and or flask?
Is enforcement of a reads from a read replica an application layer task? i.e. I have a Postgres database and I have set up a read replica. On the application side I have two connections one for the "write" database and one for the "read replica" database. In my code if I do a "read" action I use the connection to the read replica. But when I go to insert or update I use the connection to the "write" database a.k.a. master. Is there better with django or flask that this is managed automatically. i.e. I would prefer to avoid specifying directly in code the connection to use and just have django or flask figure it out on their own. -
Django: Creating my own field. AttributeError: 'NoneType' object has no attribute 'x'
I'm trying to create a custom field. It's based on postgres.JSONField. class CardiosField(JSONField): """Field representing a models.Cardios object""" def from_db_value(self, value, expression, connection): if value is None: return value return parse_cardios(value) def to_python(self, value): if isinstance(value, models.Cardios): return value if value is None: return value return parse_cardios(value) def get_prep_value(self, value): cardios_pre_json = [serie_object.pre_json() for serie_object in value.series] return json.dumps(cardios_pre_json) I've created a model that has this field: class Workout(models.Model): datetime = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) lifts = fields.LiftsField(null=True) cardios = fields.CardiosField(null=True) def __str__(self): return str(self.datetime)+" "+self.user.email __repr__ = __str__ I make migrations without a problem, but when I try to migrate, this happens: (workout) Sahands-MBP:workout sahandzarrinkoub$ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, workoutcal Running migrations: Applying workoutcal.0003_auto_20171231_2308...Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/sahandzarrinkoub/Documents/Programming/Web/Django/workout/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) … -
Django Accepting AM/PM As Form Input
I am trying to figure out how to accept am/pm as a time format in Django using a DateTime field, but I am having some trouble. I have tried setting it like this in my forms.py file pickup_date_time_from = DateTimeField(input_formats=["%m/%d/%Y %I:%M %p"]) with the following data: 12/31/2017 02:40 pm However, I get a validation error when submitting the form: (Hidden field pickup_date_time_from) Enter a valid date/time. I have also tried setting a global variable in settings.py as the documentation states: DATETIME_INPUT_FORMATS = ['%m/%d/%y %I:%M %p'] What does work is if I submit the data without the am/pm, but the output is 2017-12-31 02:40:00+00:00 Any other options? -
django test - how to get response data for future use
I'm running a login test like so: def test_login_user(self): client = APIClient() url = reverse('rest_login') data = { 'username': 'test', 'password': 'Welcome2' } response = self.client.post(url, data) self.assertEqual(response.status_code, status.HTTP_200_OK) client.logout() If I login to the app normally I see a json return like this: { "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoyLCJ1c2VybmFtZSI6ImV2YW4iLCJleHAiOjE1MTQ2NzYzNTYsImVtYWlsIjoiZXZhbkAyOGJlYXR0eS5jb20iLCJvcmlnX2lhdCI6MTUxNDY3Mjc1Nn0.8CfhfgtMLkNjEaWBfNXbUWXQMZG4_LIru_y4pdLlmeI", "user": { "pk": 2, "username": "test", "email": "test@test.com", "first_name": "", "last_name": "" } } I want to be able to grab that token value for future use however the response does not seem to have a data value to grab. -
LookupError: App 'accounts' doesn't have a 'user' model --- "App '%s' doesn't have a '%s' model." % (self.label , model_name))
I am trying to create a custom signup form for which i have extended django inbuilt user model.I am also using django-postman for user to user messaging.Postman was working quite fine till i was using inbuilt user model,however when i used the custom user model it started showing me this Lookup error(only while creating messages).I have done some research to solve this but failed. the traceback error class MadeLookupChannel(LookupChannel): File "C:\Users\vishw\Envs\Vishwesh2_env\lib\site-pack ages\ajax_select\registry.py", line 104, in MadeLookupC hannel model = get_model(app_label, model_name) File "C:\Users\vishw\Envs\Vishwesh2_env\lib\site-pack ages\ajax_select\registry.py", line 123, in get_model return apps.get_model(app_label, model_name) File "C:\Users\vishw\Envs\Vishwesh2_env\lib\site-pack ages\django\apps\registry.py", line 205, in get_model return app_config.get_model(model_name, require_rea dy=require_ready) File "C:\Users\vishw\Envs\Vishwesh2_env\lib\site-pack ages\django\apps\config.py", line 172, in get_model "App '%s' doesn't have a '%s' model." % (self.label, model_name)) LookupError: App 'accounts' doesn't have a 'user' model However i have also added this in my settings.py file in order to solve this AUTH_USER_MODEL = 'accounts.Profile' then it shows this error File "C:\Users\vishw\OneDrive\Documents\Projects_2\si mple_social_clone\simplesocial\postman\apps.py", line 1 3, in ready setup() File "C:\Users\vishw\OneDrive\Documents\Projects_2\si mple_social_clone\simplesocial\postman\models.py", line 57, in setup name_user_as = getattr(settings, 'POSTMAN_NAME_USER _AS', get_user_model().USERNAME_FIELD) AttributeError: type object 'Profile' has no attribute 'USERNAME_FIELD' this is my accounts.models.py here my Profile model extending the built in user model from django.contrib.auth.models import User from django.db … -
ValueError: Fetch argument <tf.Operation 'init_8' type=NoOp> cannot be interpreted as a Tensor
I am trying to predict by using the InceptionV3 model as the baseline model. I create the model, load the weights and predict. However; I get the above ValueError even though I have implemented the Tenserflow thread-safe model load method. The error screenshot is as follows: My code is: K.set_learning_phase(0) def baseline_model(): base_model =InceptionV3(input_shape=(299, 299, 3), weights='imagenet', include_top=False) x = base_model.output # Create model instance predictions = Dense(1, activation='sigmoid')(x) model = Model(inputs=base_model.input, outputs=predictions) for layer in base_model.layers: layer.trainable = False return model model = baseline_model() model.load_weights('weight-file.h5') graph = tf.get_default_graph() def imgEval(request): #Re-load the model onto the current request thread. global graph with graph.as_default(): Image_path = 'website_train/hello.jpg' img = load_img (Image_path) img_array = img_to_array(img) img_array /=255 img_array = img_array.reshape(1,299,299,3) y = model.predict(img_array)[0][0] print(y) return render(request, 'index.html', {}) -
Previous search on django search
Is there a way to implement going back to a previous search on a page? Example: I have an index with a search form / filters and I perform a search -> click an item in index -> display "previous search" button on this items detail view. I looked into {{ request.META.HTTP_REFERRER }} but this didn't seem to be working for me for processing the old form data on the GET request (going back to the index page). I had multiple checkboxes able to be selected so these would be added as field=1&field=2& ..... for the different options, but these weren't showing up in the url - in HTTP_REFERRER. I'd also prefer to preserve POST method so I don't have "ugly" urls, but using GET is the only way I see this being feasible. -
Django letting user filter objects with form
So I have object instances in the model and I would like to allow users to filter through them based on certain characteristics. I setup a form and added some code to handle it in the view. When the form is submitted it returns the same template but with the object filters they set. However it is not working... I was wondering why/how I should go about doing this. From: class PropertySearchForm(forms.Form): beds = forms.CharField(widget=forms.Select(attrs={'class':'form-control mb-3'}, choices=BED_CHOICES)) baths = forms.CharField(widget=forms.Select(attrs={'class':'form-control mb-3'}, choices=BATH_CHOICES)) View: def UniversityHomePageView(request,name_initials): university = get_object_or_404(University,name_initials=name_initials) listings = Listing.objects.filter(l_university=university) form = PropertySearchForm(request.GET or None) company = Company.objects.filter(c_university=university) context = { 'listings':listings, 'university':university, 'company':company, 'form':form, } if form.is_valid(): beds = int(form.cleaned_data.get('beds')) baths = int(form.cleaned_data.get('baths')) listings = Listing.objects.filter(l_university=university,beds=beds,baths=baths) return render(request,'listings/university_homepage.html',context) return render(request,'listings/university_homepage.html',context) -
celery daeminization w/ Djnago - Please explain step-by-step like I'm 5
I'm new to Python and really trying to learn things as I go. I have a Python script that pulls data from different sites and displays it to the public via a website. I am using Django with Heroku distribution. I need to automatically run my scripts in the morning to update the information. I saw that celery was the best option to do this. I now have a working example of celery, and believe that I have it properly configured with Django. However, I need to also go through a process called Daemonization as per here: http://docs.celeryproject.org/en/latest/userguide/daemonizing.html so that my celery workers can operate in the background. This is where I'm stumped, and can't find any step-by-step tutorials for this one. I think I need all of these file for things to work: /etc/init.d/celeryd /etc/defaults/celery /etc/default/celerybeat /project/celery.py /project/__init__.py I have all of these files starting in the root directory, where manage.py is located I believe I have the celery.py and __init__.py files configured correctly. Here they are: celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings') app = Celery('project') # Using a string … -
How to access deployed project in gcloud shell
Deployed a django project in gcloud in flexible environment. The changes are getting reflected in the live url. I am trying to access the deployed django project folder through gcloud shell, but not able to find it. What am i doing wrong ? -
BooleanField value return always false
I need get the value of Django form checkbox in the view.py I get the value is always False (also when its True). my code is: forms.py: class PointForm(forms.ModelForm): checkboxSGEquipTypeTagAll = forms.BooleanField(label='override', widget=forms.CheckboxInput(attrs={'id': 'checkboxSGEquipTypeTagAll'}) , required=False) View: logging.debug(form.cleaned_data['checkboxSGEquipTypeTagAll']) or: logging.debug(form['checkboxSGEquipTypeTagAll'].value()) -
Unable to get repr for class
I have 2 classes in models: class Services(models.Model): name = models.CharField(max_length=100, null=True) priority = models.IntegerField(default=1, null=True) active = models.BooleanField(default=True) def __str__(self): return self.name class MacRepairPrice(models.Model): mac_model = models.ForeignKey(MacModels, null=True) service = models.ForeignKey(Services, null=True) price = models.FloatField(default=0) active = models.BooleanField(default=True) def __str__(self): return self.mac_model Views: service_list = Services.objects.filter(active=True).order_by('-priority') for serv in service_list: price_list = MacRepairPrice.objects.filter(service_id=serv.id) here I got an error:"price_list: Unable to get repr for Don't know what's wrong? Can anyone help? -
multi imagefield from one imagefield _ django restframework
the question is : is there any proper way for creating multi Imagefields beside making multi image fields in django models? my goal is create an post model that may has multi image field but not mean it should always has.maybe one post object contain one image or may has multi image. so its not a good idea to make multi rows on database that includes null imagefield values. I checked the stackoverflow for similar questions but need to know a proper way and the solution must work in django restframework easily.any reference or help would be greateful . the question two is how to convert the size of the uploaded image for saving storage? -
Python django test case - one test failing when all tests are ran - Class variable data remaining during test
I have a dictionary which is a class variable. One test will run methods which populates this dictionary in the course of the test. There is an if statement in the code(not the tests) which basically says if dict do this. Else do this. However when i run another test which does not populate this dict the dict is already populated with the old data,and hence the if code is executed. How can i wipe the old data from the class variables -
How to return data in JSON format in Django
I want to return some data in JSON format, I created serializers.py class LocationSerializers(serializers.EmbeddedDocumentSerializer): class Meta: model = location fields = '__all__' class ProductsSerializers(serializers.DocumentSerializer): location = LocationSerializers(many=True) class Meta: model = products fields = ('picture', 'name', 'email', 'city', 'location') Models.py class location(EmbeddedDocument): type = fields.StringField() coordinates = fields.ListField(FloatField()) class products(Document): picture = fields.StringField() name = fields.StringField() email = fields.StringField() city = fields.StringField() location = fields.EmbeddedDocumentField('location') and views.py def get(self, request): prd = products.objects.all() data = ProductsSerializers(prd,many=True) return Response(data.data) When i return one product it work but wehn i want to return all didn't work I don't understand error The fields "{'_ref'}" do not exist on the document "location" -
ModuleNotFoundError: No module named 'mysite'
I have setup Python, Django and MySQL on my Windows machine. I'm trying to verify my database connection by running the following from a directory named 'zibit': > myvenv\Scripts\activate > set DJANGO_SETTINGS_MODULE=mysite.settings > django-admin dbshell After running the last command I get this error: ModuleNotFoundError: No module named 'mysite' I tried updating my wsgi.py file to the following after seeing some related posts online: import os from django.core.wsgi import get_wsgi_application import sys path = 'C:\Users\abc123\Documents\zibit' sys.path.append(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() My folder structure looks like this: zibit | +--mysite | | | +--settings.py | +--myvenv I feel like I'm missing something very simple. Any ideas? -
Django - List of tuples field
I have a django model, which would need one field that contains a list of Tuples that can be filled in by the admin in the admin view as needed. Currently, I was able to find a ListField, which is only accessible by Postgres (I am using MySQL). How would I most elegantly solve this problem? (The number of tuples which need to be filled in varies per model, so I guess creating many fields would be the sloppiest approach). Thanks in Advance -
Django custom user model creating instance along with nested object instance
I have a model 'Reader' which extends the default 'User' model: class Wishlist(models.Model): wishlist_id = models.AutoField(primary_key=True) class Reader(models.Model): user = models.OneToOneField(User) phone = models.CharField(max_length=30) address = models.CharField(max_length=80) dob = models.DateField(auto_now=False, auto_now_add=False, null=True, blank=True) # A library has many readers which_library = models.ForeignKey('Library', related_name='readers', on_delete=models.CASCADE) wishlist = models.OneToOneField(Wishlist, null=True, blank=True) #This helps to print in admin interface def __str__(self): return u"%s" % (self.user) Question 1: Can I directly create a Reader instead of User (without having to associated a reader to an existing User, which I currently see in my admin interface), and in that case how should my POST call look like? For registering new user currently I need Username, password1, password2. Question 2: While creating a Reader I also want to create a Wishlist for that Reader. How to achieve that? So far I have a serializer: class ReaderSerializer(serializers.ModelSerializer): class Meta: model = Reader fields = '__all__' #depth = 1 def create(self, validated_data): wishlist_data = validated_data.pop('wishlist') reader = Reader.objects.create(**validated_data) Wishlist.objects.create(reader=reader, **wishlist_data) return reader And a view: # Get all readers in a specific library or create a new reader @api_view(['GET', 'POST']) def reader_list(request, library_id): """ List all readers in a specific library, or create a new reader for a … -
verbose_name get uppercased in Django model
All of my model fields are shown uppercased in the admin. How can I keep them camel-cased? Thank you (Django 1.11) -
Django registration with email confirmation (new django version)
There is new version of django and some options have changed but I couldn't figure out which exactly. And I have error for token check in: {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} Error is: Reverse for 'activate' with keyword arguments '{'uidb64': b'Mw', 'token': '4sg-dd1f81a3c683bc3cf0c9'}' not found. 1 pattern(s) tried: ['activate/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] https://docs.djangoproject.com/en/2.0/releases/2.0/ I tried everything, even downloaded program that does with in authentication with older products versions but in new Django it doesn't. Can anyone help to solve this? -
Django: How to pass data via lazy reverse, but not within url
I have the lazy reverse as a link on the page which leads to form and I wish to pass some values for a subset of the field? I don't want to include the value within the path of the URL, but would be happy be part of a query or session. Thank you for your time.