Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display Django logs in templates
I'm working on a project with Python(3.6) and Django(1.10) in which I'm doing some execution in Django views.I'm printing some messages and other execution information in the console but I want to display this information inside the template which is going to be rendered after the completion of a request from Django views. Here's an example code from my Django views: # Start deployment # Setup istio on cluster service = discovery.build('container', 'v1beta1', http=views.getGoogleAuth(), cache_discovery=False) svc_req = service.projects().zones().clusters().get(projectId=deployment.project, zone=deployment.zone, clusterId=deployment.cluster) svc_res = svc_req.execute() print('Status is : {}'.format(svc_res['status'])) status = svc_res['status'] while status != 'RUNNING': svc_res = svc_req.execute() status = svc_res['status'] print('Current Status is : {}'.format(svc_res['status'])) print('Fetching Cluster configs ....') print(subprocess.call( 'gcloud container clusters get-credentials ' + deployment.cluster + ' --zone ' + deployment.zone + ' --project ' + deployment.project, shell=True)) print('Cluster is still Provisioning - Current Status is: {}'.format(status)) How can I display this log information inside Django template when the request has been completed. Help me, please! Thanks in advance! -
Django template and dynamic url
I have a few links that I need to link to via a submit button. Let's say that I have links_ 'http://link/problem1', 'http://link/problem2' and 'http://link/problem3' In my django template I'm trying to link to a random link out of those three: So in my django template I have: <a href="http://link/problem" class="btn btn-success"> Some Text </a> Is there a way that I can have a numeric loop that would loop through numbers 1 to 3 and add those numbers to the 'http://link/problem' I have found a few examaples on how to make a numeric for loop in a django template but I dont know how to add those numbers to the link in an a tag. -
prefetch_related and Prefetch object issue, filtering thru reverse Foreign Key
I have 2 models, company and Product. class Product(Meta): company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) form the database I'm trying to get the Company data and the corresponding products. From the products I want to get only the name and to be ordered descending by updated_at, created_at. I'm working with Prefetch object and prefetch_related and definitively I have multiple misunderstandings how they work. def get_queryset(self): qs = Company.objects.prefetch_related( Prefetch('products', queryset=Product.objects.only('name').order_by('-updated_at', '-created_at'))).get() return qs The error that I receive is: get() returned more than one Company Because I closed the prefetch_related method/function with ))) : I thought get() will act over the Company object and get it using the pk/slug from the url(as get do by default in DetailView). Seems that is not the case. I'm already using 'products' the related name in the Prefetch object, why in queryset is necessary to tell again the model queryset=Product.objects.... ? I was looking at the following example in django documentation: Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all() If there is 'choice_set' in Prefetch object why is called at the end choice_set.all() ? Isn't Django attached to the quesryset in prefetch_related the products to the queryset (question.choice_set) ? I think my problem is that I don't understand the order of execution, … -
Django / Geodjango / Raster / geotiff: Problems with practice task
I greet you First, I apologize for my bad english. I can read English to some extent, but I can not write well. I hope you can help me. I got a practice task, which I can not get any further. The task is the following: Project Description The goal of the projects is to create a map view similar to the Google Maps, where user can see some imagery data captured by drones. User should be able to move around the map freely, as well as zoom in and zoom out to take a closer look at the captured imagery data. It is strongly desired that the served imagery data will support transparency while minimizing the file size and bandwidth usage. This does not have to be implemented, but solution ideas are welcomed. The raw imagery data will be provided as GeoTIFF files. Imagery visible on the map can be added by placing a file inside a directory that is read by the server. Project Delivery Method Project should be delivered as a Git repository with documentation required to setup and run the project. Requirements 1. Server implementation in Python 3.5+ 2. Project must be able to run on … -
Update Django Status Field Based On Real-time Status of Celery Task?
In my model, I have a status field with a default value of 'Processing'. In the Django admin interface, after user clicks 'Save' button, the form inputs are passed to a celery task that just sleeps for 30 seconds. After that 30 seconds, how do I: determine if the celery task was successful? update the model's status field from 'Processing' to the actual status (ex: Completed, Failed? models.py from django.db import models class Scorecard(models.Model): name = models.CharField(max_length=100, unique=True) status = models.CharField(max_length=20, default='Processing') def __str__(self): return self.name admin.py from django.contrib import admin from scorecards.models import Scorecard from scorecards.tasks import get_report class ScorecardAdmin(admin.ModelAdmin): list_display = ['name', 'status'] def save_model(self, request, obj, form, change): if form.is_valid(): data = form.cleaned_data name = data['name'] get_report.delay(name) super().save_model(request, obj, form, change) admin.site.register(Scorecard, ScorecardAdmin) tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task from time import sleep @shared_task def get_report(name): sleep(30) Real-time status of the celery task updating the status field every x time intervals would be nice, but for now I'm just really curious how to do this at all. -
Contact Us form on a Django Website not sending emails
I followed the instructions from the official documentation and another Stack Overflow post to get django-contact-form working on my django website. I need it to send an email. I tried setting up a debugging server through: python -m smtpd -n -c DebuggingServer localhost:1025 I have a HTML form working with Django on the site. When I click submit on the form, it gives me an acknowledgement that my message has been sent. However, I can't see anything on the Terminal output. In my settings.py, I have the following: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 EMAIL_HOST_USER = 'my email' EMAIL_HOST_PASSWORD = 'my password' I have also tried it with the SMTP settings for Zoho mail, which is the one that I am currently using. I am not getting any emails in my inbox or the others folder either. Another thing that I have tried is changing the settings so that the emails get stored in a tmp folder. I don't want to deploy the code on the site until I can test that it works properly. Any help will be appreciated. I'm not really sure what I'm missing. Let me know if any other files are needed from … -
Django: Sum Total value over Foreign Key Data
I am using Django 1.11 and Python3.5 I have created a table. This is a screenshot. When I got a table from my query database, it is showing 10+2+3... but I want to get total sum value for every customer within Due Taka update column in table like this 10+2+4+2 = 18 this is my model.py file class CustomerInfo(models.Model): customer_name = models.CharField('Customer Name', max_length=100) customer_mobile_no = models.CharField( 'Mobile No', null=True, blank=True, max_length=12) customer_price=models.IntegerField('Customer Price',default=1) customer_product_warrenty = models.CharField('Product Warrenty',null=True, blank=True,max_length=10) customer_sell_date = models.DateTimeField('date-published', auto_now_add=True) customer_product_id=models.CharField('Product ID',max_length=300,null=True, blank=True) customer_product_name=models.TextField('Product Name') customer_product_quantity=models.IntegerField('Quantity',default=1) customer_uid = models.CharField(max_length=6, blank=True, null=True) customer_info=models.TextField('Customer Details Informations', blank=True, null=True) customer_conditions=models.CharField('Conditions',blank=True, null=True, max_length=300) customer_due_taka_info=models.IntegerField(default=0) customer_discount_taka=models.IntegerField(default=0) customer_first_time_payment=models.IntegerField('First Time Payment',default=0) customer_first_due_info = models.CharField('First Due Info',default='No due info', max_length=200, blank=True, null=True) customer_product_mrp=models.IntegerField('Products MRP', default=0) customers_refrence=models.CharField(max_length=100) customer_updated = models.DateTimeField(auto_now=True) customer_type=models.CharField('Customer Type', default='MobilePhone', max_length=50) def __str__(self): return self.customer_name def remainBalance(self): if self.customer_price > self.customer_due_taka_info: remain=self.customer_price - self.customer_due_taka_info return remain def totalRetalsPerSingle(self): return self.customer_product_quantity * self.customer_product_mrp #def product_warrenty(self): #expire_date_oneyr =self.customer_sell_date+ datetime.timedelta(days=365) #return 'This product expire on this date ' + str(expire_date_oneyr) class Meta: verbose_name = ("গ্রাহকের তথ্য") verbose_name_plural = ("গ্রাহকের তথ্যসমূহ") #intregated with Customerinfo Model (Using foreignKey) class DueTaka(models.Model): customer_due = models.IntegerField('Due Taka', default=0) customer_due_date=models.DateTimeField(auto_now_add=True) customer_due_info=models.CharField('Due Info', max_length=200, blank=True, null=True) customerinfo = models.ForeignKey(CustomerInfo, on_delete=models.CASCADE) due_customer_updated = models.DateTimeField(auto_now=True) … -
Django View Usage
I'm still quite confused on when to use a View in django A view returns a webpage back or a HttpResponse. Suppose my website had a button "Get total" that adds up the numbers in a user-inputted checkbox To give this button functionality, what are the steps I would take? Would pressing the button call a URL, which would call a view, which would return a response? How would I "fetch" this response? I'm sorry this is vague, but I don't know what I need to search to be able to do the above using Django. Is this an example of REST? I want to create a form that can be processed by Django and then return a response to the user such as "Answer is correct", without refreshign the webpage. I am using django 1.11, I've been working with django for like a month now, and I"m starting to get better everyday (I can use models and all the similar stuff alright) but I'm stuck at this point forward -
How to embed related data in Django from models?
I've been working on Django since couple of days. I know how to get what I want in Laravel but I need help in Django. Suppose I have two tables. authors and books books table contain: id, name, author authors table contain: id, name With Laravel, I can just add a function which gives relationship between books and authors and Book::with('authors') will give me all the data of books along with extra field author which contains detail of the author of the book. I don't know how to do this Eager Loading with Django. -
'no [query] registered for [filtered]'
I am using haystack with elasticsearch backend for full text searching. I am wanting to show the search result using ajax. However I am getting an error of elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception', 'no [query] registered for [filtered]') . I build the index using python manage.py rebuild_index --verbosity=2 and it showed me 4 furnitured indexed as well I am just into this so I did not understand the below solution Django/Haystack error: elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception',...) Here filter should be replace with bool solution is provided but i dont know where is that file to change version of library used Django==1.11.6 elasticsearch==5.6.1 django-haystack==2.6.1 -
Django Model Factory get or create
I have a Django Model defined like below class CustomModel(models.Model): column = models.CharField(max_length=50, unique=True) Define a Factory for the model class CustomModelFactory(DjangoModelFactory): column = 'V1' FACTORY_FOR = CustomModel How do i make sure that factory implements get_or_create instead of a create everytime ? Does anyone know how can this be done ? -
Where is my django installation in windows 7
I use Django but I need to find the default templates and applications. I don't know where it's installed. How can I find that ? -
Can't load statics Django
Project structure: project_folder ├── apps │ ├── app1 │ ├── app2 ├── static │ ├── css │ │ ├── bootstrap.min.css │ ├── images │ └── js │ │ ├── bootstrap.min.js ├── templates │ ├── base │ │ ├── base.html Here is my settings.py: STATIC_PATH = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIR = [ STATIC_PATH, ] I got this response: [10/Dec/2017 02:43:58] "GET /static/css/bootstrap.min.css HTTP/1.1" 404 1676 [10/Dec/2017 02:43:58] "GET /static/images/Logo-ISCAV.png HTTP/1.1" 404 1676 [10/Dec/2017 02:43:58] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 1670 [10/Dec/2017 02:43:58] "GET /static/js/bootstrap.min.js HTTP/1.1" 404 1670 And here are some tags in the HTML {% load staticfiles %} <!DOCTYPE html> <html lang="es-CL"> <head> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta charset="UTF-8"> <title>ISCAV | {% block title %}{% endblock %}</title> <!-- Carga el path de los archivos estaticos y estilos --> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> {% block extrastatic %} {% endblock extrastatic %} </head> I can't see what is wrong. -
Django ModelMultipleChoiceField Form
On my website, I've got a "Compose Email" page with three fields - Subject, Recipients, & Body. In my database, I've got this custom user model in models.py: class MyUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) school = models.CharField(max_length=100) def __unicode__(self): return self.user I want to create a form to import contacts that includes all of the MyUser objects. Currently, I've got this in forms.py: class ContactForm(forms.Form): contacts = forms.ModelMultipleChoiceField(widget=forms.Select(attrs={'size':'13', 'onchange':'this.form.action=this.form.submit()'}), queryset=MyUser.objects.all().order_by('user'))#, empty_label=None) def __init__(self, *args, **kwargs): super(ContactForm, self).__init__(*args, **kwargs) self.fields['contacts'].queryset = MyUser.objects.all() In my views.py, I've got the following view: def import_contacts(request): contact_form = ContactForm() if request.method == "POST": contact_form = ContactForm(request.POST) if contact_form.is_valid: # send data to be processed return render(request, 'compose_email.html', { 'contact_form': contact_form, }) errors = contact_form.errors or None # form not submitted or it has errors return render(request, 'apple/contact_import_form.html', { 'contact_form': contact_form, 'errors': errors, }) return render(request, 'apple/contact_import_form.html', {'ContactForm': form}) contact_import_form.html ... <div class="form-panel"> <form method="post"> {% csrf_token %} {{ form.as_p }} <div id="sub"> <button type="submit" class="button">Add</button> </div> </form> </div> ... And finally, here is the .html file from which I link to import_contact_form.html compose_email.html: ... <a class="emailButton" id="b1" href="/gordie/home/templates/">Import Template</a> <a class="emailButton" id="b2" href="/home/send_email/import_contacts/">Import Contacts</a> <!-- <button class="emailButton" id='b2'>Import Contacts</button> --> <div class="form-panel"> <form method="post"> {% … -
whatsapp has banned my 3 mobile numbers
I am developing an application in django which will listen whatsapp messages and echo back to corresponding sender. I am using selenium webdriver in python and javascript to do this. Following code is the 'whatsapp_login' view function which launches a firefox instance in which I read the qrcode and login at https://web.whatsapp.com/ from django.http import HttpResponse from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import json from django.core import serializers from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait import os from django.views.decorators.csrf import csrf_exempt driver = None @csrf_exempt def whatsapp_login(request): global driver profile = webdriver.FirefoxProfile() profile.accept_untrusted_certs = True driver = webdriver.Firefox(firefox_profile=profile) driver.get('https://web.whatsapp.com/') script_path = os.path.dirname(os.path.abspath(__file__)) script = open(os.path.join(script_path, "jquery.js"), "r").read() driver.execute_script(script) script_path = os.path.dirname(os.path.abspath(__file__)) script = open(os.path.join(script_path, "add_eventlistener.js"), "r").read() driver.execute_script(script) resp = HttpResponse('show qrcode page') return resp I have passed the 'jquery.js' and my 'add_listener.js' files to selenium webdriver's 'execute_script' method. 'add_listener.js' script contains MutationObserver code which adds listener to each of contact list in whatsapp web. Following is my 'add_listener.js' code var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { if(mutation.attributeName === 'class') { var attributeValue = $(mutation.target).prop(mutation.attributeName); console.log("attributeValue: "+attributeValue); if(attributeValue.indexOf('hover') > -1) { var user … -
How to Rehydrate React Components of Python App with Server-side Rendering
I'm using the python-react library to create a Django app with server-side rendering of react components. Although I've implemented basic rendering successfully, I've been unable to rehydrate the DOM - so React event handlers aren't working. Any thoughts on how to resolve? I've tried including a script tag with a webpack bundle. My code closely resembles an app the docs provided as a basic example; that app is available here: https://github.com/markfinger/python-react/tree/master/examples/basic_rendering. Please note that the example app uses Flask. -
Writing nested queries in Django
I am trying to write a nested query in Django. It is very simple to do in SQL, but with Django I am having some trouble deciding if I am doing it right or not. I have three models. Area, Location, and Measurement. Area class Area(models.Model): name = models.CharField(max_length=200) longitude = models.FloatField() latitude = models.FloatField() Location class Location(models.Model): name = models.CharField(max_length=200) altitude = models.IntegerField() area = models.ForeignKey(Area, on_delete=models.CASCADE) Measurement class Measurement(models.Model): value = models.FloatField() date = models.DateTimeField() location = models.ForeignKey(Location, on_delete=models.CASCADE) Inside Area, I need a function that will return the average of the measurements for this area. So basically, I need the average measurements of all locations for this area. Area can have many locations, but locations can have one area. In the Area Model, I made this function: def average_measurement(self): all_locations = self.location_set.all() return all_locations.measurement_set.all().aggregate(Avg('value')) This is my equivalent to writing a nested query in Django. I get all locations first and then find the average of all their measurements. Am I doing this correctly? On a side question, would this query be equivalent to doing something like this: avg = 0 locations = self.location_set.all() sum = 0 counter = 0 for l in locations: measurement = l.measurement_set.all() … -
migration error with Django 1.8
I'm brand new to Django and Python. So I git cloned the code from my team's repo. Then I started virtualenv, and did pip3 install -r requirements.txt. started the server. I think I also installed sqlite3/sqlite/mysql. i made some changes to db through 127.0.0.1:8000/admin. then i couldn't find the added info in homepage. So i ran python manage.py migrate. Terminal return this error: Traceback (most recent call last): File "manage.py", line 16, in execute_from_command_line(sys.argv) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/init.py", line 338, in execute_from_command_line utility.execute() File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/init.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/base.py", line 393, in run_from_argv self.execute(*args, **cmd_options) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute output = self.handle(*args, **options) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 25, in handle call_command("migrate", **options) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/init.py", line 120, in call_command return command.execute(*args, **defaults) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/base.py", line 444, in execute output = self.handle(*args, **options) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in init self.loader = MigrationLoader(self.connection) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in init self.build_graph() File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/db/migrations/loader.py", line 299, in build_graph _reraise_missing_dependency(migration, parent, e) File "/Users/SamNYiran/Desktop/CodingLife/nutrition/lib/python2.7/site-packages/django/db/migrations/loader.py", line 282, in _reraise_missing_dependency raise exc django.db.migrations.graph.NodeNotFoundError: Migration contenttypes.0002_remove_content_type_name dependencies reference nonexistent parent node (u'contenttypes', u'0001_initial') i removed all the pyc files, still the same error python 2.7 Django 1.8 -
How to store a DOMDocument (Node) object in Django?
Background I would like to store the text a user is highlighting when they click a button. I first get the Range from a user's selection with window.getSelection().getRangeAt(0). Given this [Range] object, I would like to be able to store some data in my Django server so that when another user visits my website, they can see what others highlighted. If you know the answer, stop reading here. The following are solutions I have considered. I am wondering how I could do this most efficiently. Possible Solutions: Creating a Node Field in Django. I am not extremely experienced in Django. However, I was wondering if it would be possible to write a custom Django Field which stores a Range or Field object. It would be ideal for the field to work like so: script.js function getSelectionRange() { return window.getSelection().getRangeAt(0); } $.post({ url: "http://127.0.0.1:8000/range/", data: { string_key: foo().toString(), ... range: getSelectionRange() }, processData: false }); views.py ... range = Range.objects.create(range=request.POST.get('range') ... or, with a field for Node objects: ... first_node = Node.objects.create(node=request.POST.get('first_node') end_node = Node.objects.create(node=request.POST.get('end_node') ... Would the ajax call work? Would string values be a Python str in my views.py using request.POST.get('string_key')? Reconstructing the Range object using its constructor: The … -
Django, Creating multiple forms for one sumbit button, using crispy and generic views
I want to create a Person and Assign that Person to a room with the same Form, Model is like Person --> Room using foreign key idPerson Model Person class Persona(models.Model): nombre = models.CharField(max_length=50) apellido_paterno = models.CharField(max_length=50) apellido_materno = models.CharField(max_length=50) id_documento = models.CharField(max_length=50) id_tipo_documento = models.ForeignKey(TipoDocumento, on_delete=models.CASCADE) id_genero = models.ForeignKey(Genero, on_delete=models.CASCADE) fecha_nacimiento = models.DateField(auto_now=False, auto_now_add=False, default= datetime.now) def get_absolute_url(self): return reverse('residentes:detalle', kwargs={'pk': self.pk}) def __str__(self): return self.nombre + ' - ' + self.apellido_paterno class Meta: unique_together = ('id_documento', 'id_tipo_documento') Model Resident class Residente(models.Model): persona = models.ForeignKey(Persona, on_delete=models.CASCADE) unidad_alquiler = models.CharField(max_length=5) tipo = models.CharField(max_length=50) fotografia = models.CharField(max_length=500) activo = models.BooleanField(default=True) def __str__(self): return str(self.persona.pk) + '-' + self.tipo + ' - ' + self.persona.nombre + ' ' + self.persona.apellido_paterno Views class ResidenteCreate(CreateView): model = Residente template_name = 'residentes/residente_form.html' form_class = ResidenteForm second_form_class = PersonaForm success_url = reverse_lazy('residentes:detalle') def get_context_data(self, **kwargs): context = super(ResidenteCreate, self).get_context_data(** kwargs) if 'form' not in context: context['form'] = self.form_class(self.request.GET) if 'form2' not in context: context['form2'] = self.second_form_class(self.request.GET) return context def post(self, request, *args, **kwargs): self.object = self.get_object form = self.form_class(request.POST) form2 = self.second_form_class(request.POST) if form.is_valid() and form2.is_valid(): residente = form.save(commit=False) residente.persona = form2.save() residente.save() return HttpResponseRedirect(self.get_success_url()) else: return self.render_to_response(self.get_context_data(form=form, form2=form2)) I see the 2 forms as one, … -
How can I upgrade PostgreSQL database on Heroku?
I am going to upgrate plan on Heroku with my Django app from hobby-dev to hobby-basic. At the moment heroku pg:info returns: Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 9.6.4 Created: 2017-11-12 19:20 UTC Data Size: 135.9 MB Tables: 19 Rows: 1272760/10000 (Above limits, access disruption imminent) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql- ... I tried to use Upgrading Heroku Postgres Databases but I am not sure which way should I choose. It seems to be that pg:copy would be the best idea? I think that steps in this case should look as shown below, am I right? 1.heroku addons:create heroku-postgresql:standard-0 2.heroku pg:wait 3.heroku maintenance:on 4.heroku pg:copy DATABASE_URL HEROKU_POSTGRESQL_PINK --app sushi How can I check DATABASE_URL and HEROKU_POSTGRESQL_PINK? I guess that DATABASE_URL is in Config Vars and this is it postgres://gxapb...2840@ec2-77-131-196-1207.compute-1.amazonaws.com:5432/d...md, isn't it? But how can I generate HEROKU_POSTGRESQL_PINK? I found information that it is the target database. 5.heroku pg:promote HEROKU_POSTGRESQL_PINK 6.heroku maintenance:off -
AttributeError at /accounts/regist_save/ 'User' object has no attribute 'user'
AttributeError at /accounts/regist_save/ 'User' object has no attribute 'user' error happens.I wrote in views.py I wrote in views.py def regist(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) context = { 'regist_form': regist_form, 'profile_form': profile_form, } return render(request, 'registration/regist.html', context) @require_POST def regist_save(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid(): regist = regist_form.save(commit=False) regist.is_staff = True regist.save() profile = profile_form.save(commit=False) profile.user = regist.user sex = request.POST.get("sex", "") year = request.POST.get("year", "") month = request.POST.get("month", "") day = request.POST.get("day", "") profile.sex = sex profile.year = year profile.month = month profile.day = day profile.save() else: print(regist_form.errors) print(profile_form.errors) return render(request, 'registration/detail.html') in regist.html <div class="form-group-lg"> <label for="id_username">Username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">Email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">Password</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">Password2</label> {{ regist_form.password2 }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> {% load static %} <div class="form-group-lg"> <label for="birthday">Date</label> <select id="year" class="form-control year" name="year"> <option value="">--</option> </select> Year <select id="month" class="form-control month" name="month"> <option value="">--</option> </select> Month <select id="day" class="form-control day" name="day"> <option value="">--</option> </select> Day <br> <br> </div> <div class="form-group-lg"> <label for="sex">SEX</label> <select id="sex" class="form-control sex" name="sex"> <option value="">--</option> <option value="male">male</option> … -
localhost:9200 shows elasticsearch version as 6.0.1 after reinstalling 5.0.1
Previously I tried using elasticsearch 6 with django-haystack 2.6.1 for full text searching. I came to know that haystack does not support elasticsearch v6 so I deleted it. The steps I did for deleting and reinstalling are rm -rf es/ (I copied the elasticsearch in this folder) I downloaded the elasticsearch 5.0.1 from official website mv Downloads/elasticsearch-5.0.1.tar.gz es/ tar -zxvf elasticsearch-5.0.1.tar.gz cd elasticsearch-5.0.1 ./bin/elasticsearch -d I then run the following command in the terminal curl -XGET 'http://localhost:9200' My configuration HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'haystack_furnitures', }, } The tech I am using macos, django==1.11.6, django-haystack==2.6.1, elasticsearch==5.0.1 and elasticsearch in a system the same version -
Why do I need to create a virtual environment for my public Django application?
I've been running my Django project (website) in my local virtual environment. However I now want to go live and make the website public - so I've created my remote server on Digital Ocean, and have been following it's tutorial on settings up Django. However I've reached this point in the tutorial where it says to create a virtual environment. I thought virtual environments were only used for testing your application offline? Why do I need a virtual environment for my application running on a remote server? -
Angular + DJango or Angular + Node Js
which one is best combination for e-commerce website with chatting functionality and Google Maps? First is Angular + DJango and second is Angular + Node. Why one of them is better? Which is easy to learn and manage?